Complete Python List cheatsheet with clear examples for quick revision
To add an item to a list.
l1 = [12, 23, 34, 56] l1.append(3.14) # [12, 23, 34, 56, 3.14]
To add all elements of another list to a list.
l1 = [12, 23, 34, 56] l2 = ['a', 'b', 'c'] l1.extend(l2) # [12, 23, 34, 56, 'a', 'b', 'c']
To add an item at a particular index in a list.
l1 = [12, 23, 34, 56] l1.insert(2, 420) # [12, 23, 420, 34, 56]
To remove the first occurrence of an item from the list.
l1 = [12, 23, 34, 56] l1.remove(34) # [12, 23, 56]
To remove an item from the list by index and return it.
l1 = [12, 23, 34, 56] l1.pop(1) # returns 23, l1 becomes [12, 34, 56]
Returns the index of the first matching item.
l1 = [12, 23, 34, 56] l1.index(23) # 1
Returns how many times an item appears in the list.
l1 = [12, 23, 34, 56, 34, 34] l1.count(34) # 3
Sorts the list in ascending order in place.
l1 = [90, 121, 1, 2, 23, 34, 5, 6] l1.sort() # [1, 2, 5, 6, 23, 34, 90, 121]
Reverses the items of the list in place.
l1 = [90, 121, 1, 2, 23, 34, 5, 6] l1.reverse() # [6, 5, 34, 23, 2, 1, 121, 90]
Returns a shallow copy of the list.
l1 = [90, 121, 1, 2, 23, 34, 5, 6] l2 = l1.copy() # [90, 121, 1, 2, 23, 34, 5, 6]
Removes all items from the list.
l1 = [90, 121, 1, 2, 23, 34, 5, 6] l1.clear() # []
Last updated 24 days ago