Python: List Methods
All list methods modifies the list in-place.
Append to List
note: you can also join lists by
list1 + list2
list.append(x)
- Append x to the end.
xx = [1, 2, 3] xx.append("a") print(xx == [1, 2, 3, "a"])
xx = [1, 2, 3] xx.append(["a"]) print(xx == [1, 2, 3, ["a"]])
list.extend(x)
- Append x to the end, but flatten x one level if its a list.
xx = [1, 2, 3] xx.extend(["a"]) print(xx == [1, 2, 3, "a"])
Insert an Item
list.insert(i, x)
- Insert at i. Same as
list[i:i] = [x]
xx = [1, 2, 3] xx.insert(1, "a") print(xx == [1, "a", 2, 3])
Pop, Remove First Item
list.pop()
- Remove last item and return that item.
list.pop(i)
- Remove ith item and return that item.
Find Item
list.index(x)
- Return the index of first occurrence of x. Error if x is not in list.
xx = [0, 1, 2, 3, 4, 5, 6, 9, 8, 9] print(xx.index(3) == 3)
list.index(x, i)
- Start at index i
Best to think of index as between items. The left of first item is 0.
xx = ["a", "b", "c"] print(xx.index("b", 1) == 1) # print(xx.index('b', 2)) # ValueError: 'b' is not in list
list.index(x, i, j)
- search between index j and j
list.remove(x)
- Remove first occurrence of x.
return
None
. Error if x is not in list.xx = [0, 1, 2, 3] print(xx.remove(2) == None) print(xx == [0, 1, 3])
Find and count
list.count(x)
- Return the number of occurrences of x
print([1, 2, 3, 2, 7, 2].count(2) == 3)