Python: List Methods

By Xah Lee. Date: . Last updated: .

Append to List

list.append(x)

Append x to the end.

if x is a list, it's added as a nested list.

xx = [1, 2, 3]
xx.append("a")
print(xx)
# [1, 2, 3, 'a']
# if arg is a list, it is added as as list

xx = [1, 2, 3]
xx.append(["a", "b"])
print(xx)
# [1, 2, 3, ['a', 'b']]

Append List Elements

list.extend(listB)

Append listB items to the end.

xx = [1, 2, 3]
xx.extend(["a", "b"])
print(xx)
# [1, 2, 3, 'a', 'b']

Join Lists

you can also join lists by list1 + list2

it creates a new list.

Insert One Item

list.insert(i, x)

Insert at i.

xx = [1, 2, 3]
xx.insert(1, "a")

print(xx)
# [1, 'a', 2, 3]

Pop, Remove and Return Last Item (or ith)

list.pop()

Remove last item and return that item. List is modified.

xx = [1, 2, 3]
yy = xx.pop()

print(yy)
# 3

print(xx)
# [1, 2]
list.pop(i)

Remove ith item and return that item.

xx = [1, 2, 3]
yy = xx.pop(0)

print(yy)
# 1

print(xx)
# [2, 3]

Find Item

list.index(x)
  • Return the index of first occurrence of x.
  • Error if x is not in list.
xx = [0, 1, 2, "a", 4]
print(xx.index("a"))
# 3
list.index(x, i)

Start at index i

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

Remove Element by Value

list.remove(x)
  • Remove first occurrence of x.
  • return None.
  • Error if x is not in list.
xx = [0, 1, "t", 3]
print(xx.remove("t"))
# None

print(xx)
# [0, 1, 3]

Count Occurrence of a Value

list.count(x)

Return the number of occurrences of x

print([1, 2, 3, 2, 7, 2].count(2))
# 3

Sort and Reverse

Python, Data Structure