Python - List

In Python, the list is a mutable sequence type. A list object contains one or more items of different data types in the square brackets [] separated by a comma. The following declares the lists variable.

Example: List Type
mylist=[] # empty list

names=["Jeff", "Bill", "Steve", "Mohan"] # string list

item=[1, "Jeff", "Computer", 75.50, True] # list with heterogeneous data

A list can contain unlimited data depending upon the limitation of your computer's memory.


List items can be accessed using a zero-based index in the square brackets []. Indexes start from zero and increment by one for each item. Accessing an item using a large index than the list's total items would result in IndexError.

Example: Access List Values using Indexes
names=["Jeff", "Bill", "Steve", "Mohan"] 
print(names[0]) # returns "Jeff"
print(names[1]) # returns "Bill"
print(names[2]) # returns "Steve"
print(names[3]) # returns "Mohan"
print(names[4]) # throws IndexError: list index out of range

A list can contain multiple inner lists as items that can be accessed using indexes.

Example: Access List Values using Indexes
nums=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10] 

print(nums[0]) # returns 1
print(nums[1]) # returns 2
print(nums[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(nums[4]) # returns 10
print(nums[3][0]) # returns 4
print(nums[3][3]) # returns [7, 8, [9]]
print(nums[3][3][0]) # returns 7
print(nums[3][3][2]) # returns [9]

List Class

All the list objects are the objects of the list class in Python. Use the list() constructor to convert from other sequence types such as tuple, set, dictionary, string to list.

Example: List Class



nums=list((10, 20, 30))

nums=list({100, 200, 300})

Iterate List

A list items can be iterate using the for loop.

Example: Iterate List
names=["Jeff", "Bill", "Steve", "Mohan"] 

for name in names:

Update List

The list is mutable. You can add new items in the list using the append() or insert() methods, and update items using indexes.

Example: Update List Values
names=["Jeff", "Bill", "Steve", "Mohan"] 
names[0]="Newton" # update 1st item at index 0
names[1]="Ram" # update 2nd item at index 1

names.append("Abdul") # adds new item at the end

["Newton", "Ram", "Steve", "Mohan", "Abdul"]

Be careful, an error "index out of range" will be thrown if the element at the specified index does not exist.

Remove Items

Use the remove(), pop() methods, or del keyword to delete the list item or the whole list.

Example: Remove List Values
names=["Jeff", "Bill", "Steve", "Mohan"] 
del names[0] # removes item at index 0
print("After del names[0]: ", names)

names.remove("Bill") # removes "Bill"
print("After names.remove("Bill"): ", names)

print(names.pop(0)) # return and removes item at index 0
print("After names.pop(0): ", names)

names.pop() # return removes item at last index
print("After names.pop(): ", names)

del names # removes entire list object
print(names) #error
After del names[0]: ["Bill", "Steve", "Mohan"]
After names.remove("Bill"): ["Steve", "Mohan"]
After names.pop(0):["Mohan"]
After names.pop(): []
NameError: name 'names' is not defined

List Operators

Like the string, the list is also a sequence. Hence, the operators used with strings are also available for use with the list (and tuple also).

Operator Example
The + operator returns a list containing all the elements of the first and the second list.
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> L1+L2     
[1, 2, 3, 4, 5, 6]
The * operator concatenates multiple copies of the same list.
>>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The slice operator [] returns the item at the given index. A negative index counts the position from the right side.
>>> L1=[1, 2, 3]
>>> L1[0] 
>>> L1[-3]
>>> L1[1] 
>>> L1[-2]
>>> L1[2]
>>> L1[-1] 
The range slice operator [FromIndex : Untill Index - 1] fetches items in the range specified by the two index operands separated by : symbol.
If the first operand is omitted, the range starts from the index 0. If the second operand is omitted, the range goes up to the end of the list.
>>> L1=[1, 2, 3, 4, 5, 6]
>>> L1[1:]
[2, 3, 4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[1:4]
[2, 3, 4]           
>>> L1[3:] 
[4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[-5:-3]
[2, 3]
The in operator returns true if an item exists in the given list.
>>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1     
>>> 10 in L1             
The not in operator returns true if an item does not exist in the given list.
>>> L1=[1, 2, 3, 4, 5, 6]
>>> 5 not in L1          
>>> 10 not in L1         

List Methods

List Method Description
list.append() Adds a new item at the end of the list.
list.clear() Removes all the items from the list and make it empty.
list.copy() Returns a shallow copy of a list.
list.count() Returns the number of times an element occurs in the list.
list.extend() Adds all the items of the specified iterable (list, tuple, set, dictionary, string) to the end of the list.
list.index() Returns the index position of the first occurance of the specified item. Raises a ValueError if there is no item found.
list.insert() Inserts an item at a given position.
list.pop() Returns an item from the specified index position and also removes it from the list. If no index is specified, the list.pop() method removes and returns the last item in the list.
list.remove() Removes the first occurance of the specified item from the list. It the specified item not found then throws a ValueError.
list.reverse() Reverses the index positions of the elements in the list. The first element will be at the last index, the second element will be at second last index and so on.
list.sort() Sorts the list items in ascending, descending, or in custom order.