Python List Methods with Examples
1. append()
Adds a single element at the end of the list.
Example 1:
lst = [1, 2]
lst.append(3) # [1, 2, 3]
Example 2:
lst.append([4, 5]) # [1, 2, 3, [4, 5]]
2. extend()
Adds all elements from another list.
Example 1:
lst = [1, 2]
lst.extend([3, 4]) # [1, 2, 3, 4]
Example 2:
lst.extend("hi") # [1, 2, 3, 4, 'h', 'i']
3. insert(index, item)
Inserts item at the given index.
Example 1:
lst = [1, 3]
lst.insert(1, 2) # [1, 2, 3]
Example 2:
lst.insert(0, "start") # ['start', 1, 2, 3]
4. remove(item)
Removes the first occurrence of the item.
Example 1:
lst = [1, 2, 3, 2]
lst.remove(2) # [1, 3, 2]
Example 2:
lst.remove(1) # [3, 2]
5. index(item)
Returns the index of the first occurrence.
Example 1:
lst = ['a', 'b', 'c', 'a']
print(lst.index('a')) # 0
Example 2:
print(lst.index('c')) # 2
6. count(item)
Returns how many times an item appears.
Example 1:
Python List Methods with Examples
lst = [1, 2, 2, 3]
print(lst.count(2)) # 2
Example 2:
print(lst.count(4)) # 0
7. pop(index)
Removes and returns item at index (last if no index).
Example 1:
lst = [1, 2, 3]
print(lst.pop()) # 3, lst becomes [1, 2]
Example 2:
print(lst.pop(0)) # 1, lst becomes [2]
8. reverse()
Reverses the list in-place.
Example 1:
lst = [1, 2, 3]
lst.reverse() # [3, 2, 1]
Example 2:
lst2 = ['a', 'b']
lst2.reverse() # ['b', 'a']
9. sort()
Sorts the list in ascending order by default.
Example 1:
lst = [3, 1, 2]
lst.sort() # [1, 2, 3]
Example 2:
lst2 = ['c', 'a', 'b']
lst2.sort() # ['a', 'b', 'c']
10. copy()
Returns a shallow copy of the list.
Example 1:
lst = [1, 2, 3]
new_lst = lst.copy() # [1, 2, 3]
Example 2:
print(new_lst == lst) # True, but different objects
11. clear()
Removes all elements from the list.
Example 1:
lst = [1, 2, 3]
lst.clear() # []
Python List Methods with Examples
Example 2:
lst2 = ['a', 'b']
lst2.clear() # []