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.

mylist=[] # empty list
print(mylist)

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

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

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

nums=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]

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.

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.

nums=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10] 
print(names[0]) # returns 1
print(names[1]) # returns 2
print(names[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(names[4]) # returns 10
print(names[3][0]) # returns 4
print(names[3][3]) # returns [7, 8, [9]]
print(nums[3][3][0]) # returns 7
print(nums[3][3][2]) # returns [9]
Output:
1
2
[4, 5, 6, [7, 8, [9]]]
10
4
[7, 8, [9]]
7
[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.

nums=[1,2,3,4]
print(type(nums))

mylist=list('Hello')
print(mylist)

nums=list({1:'one',2:'two'})
print(nums)

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

nums=list({100, 200, 300})
print(nums)
Output:
<class 'list'>
['H', 'e', 'l', 'l', 'o']
[1, 2]
[10, 20, 30]
[100, 200, 300]

Iterate List

A list items can be iterate using the for loop.

names=["Jeff", "Bill", "Steve", "Mohan"] 

for name in names:
    print(name)
Output:
Jeff
Bill
Steve
Mohan

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.

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

print(names)
Output:
["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.

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)
Output:
After del names[0]: ["Bill", "Steve", "Mohan"]
After names.remove("Bill"): ["Steve", "Mohan"]
"Steve"
After names.pop(0):["Mohan"]
"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] 
1                  
>>> L1[-3]
1
>>> L1[1] 
2
>>> L1[-2]
2
>>> L1[2]
3
>>> L1[-1] 
3
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     
True                     
>>> 10 in L1             
False
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          
False            
>>> 10 not in L1         
True

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.