Python Cheat Sheet: List Methods
“A puzzle a day to learn, code, and play” → Visit finxter.com
Method Description Example
lst.append(x) Appends element x to the list lst. >>> l = []
>>> l.append(42)
>>> l.append(21)
[42, 21]
lst.clear() Removes all elements from the list >>> lst = [1, 2, 3, 4, 5]
lst–which becomes empty. >>> lst.clear()
[]
lst.copy() Returns a copy of the list lst. Copies only >>> lst = [1, 2, 3]
the list, not the elements in the list (shallow >>> lst.copy()
[1, 2, 3]
copy).
lst.count(x) Counts the number of occurrences of >>> lst = [1, 2, 42, 2, 1, 42, 42]
element x in the list lst. >>> lst.count(42)
3
>>> lst.count(2)
2
lst.extend(iter) Adds all elements of an iterable iter (e.g. >>> lst = [1, 2, 3]
another list) to the list lst. >>> lst.extend([4, 5, 6])
[1, 2, 3, 4, 5, 6]
lst.index(x) Returns the position (index) of the first >>> lst = ["Alice", 42, "Bob", 99]
occurrence of value x in the list lst. >>> lst.index("Alice")
0
>>> lst.index(99, 1, 3)
ValueError: 99 is not in list
lst.insert(i, x) Inserts element x at position (index) i
in >>> lst = [1, 2, 3, 4]
the list lst. >>> lst.insert(3, 99)
[1, 2, 3, 99, 4]
lst.pop() Removes and returns the final element of >>> lst = [1, 2, 3]
the list lst. >>> lst.pop()
3
>>> lst
[1, 2]
lst.remove(x) Removes and returns the first occurrence >>> lst = [1, 2, 99, 4, 99]
of element x in the list lst. >>> lst.remove(99)
>>> lst
[1, 2, 4, 99]
lst.reverse() Reverses the order of elements in the list >>> lst = [1, 2, 3, 4]
lst. >>> lst.reverse()
>>> lst
[4, 3, 2, 1]
lst.sort() Sorts the elements in the list lst in >>> lst = [88, 12, 42, 11, 2]
ascending order. >>> lst.sort()
# [2, 11, 12, 42, 88]
>>> lst.sort(key=lambda x: str(x)[0])
# [11, 12, 2, 42, 88]