← Python lessons

Python List Methods: insert(), pop(), sort(), index() and count()

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

List methods are the actions a list can do on itself: insert(), pop(), extend() and sort() change it; index() and count() search it.

Read Lists first: this lesson assumes .append(), .remove() and in.

Add and take out at any position

insert(i, x) puts x before position i. pop() removes the last item and gives it back; pop(i) removes the item at i.

queue = ["Ada", "Sam"]
queue.insert(0, "Mia")
print(queue)
last = queue.pop()
print(last)
first = queue.pop(0)
print(first)
print(queue)

Use pop() when you need the removed item. Use remove(x) when you know the value, not the position.

Add several items with extend()

append() adds its argument as one item. extend() adds each item of it.

a = [1, 2]
a.append([3, 4])
print(a)
b = [1, 2]
b.extend([3, 4])
print(b)

a now holds a list inside a list. b holds four numbers.

Sort in place or make a sorted copy

sort() changes the list and returns None. sorted() returns a new list.

scores = [5, 9, 2]
print(sorted(scores))
print(scores)
scores.sort(reverse=True)
print(scores)
print(scores.sort())

The last line prints None. So never write scores = scores.sort() — it throws the list away. Use sorted() when you must keep the original order.

Search with index() and count()

index(x) gives the position of the first x. count(x) says how many there are.

rolls = [3, 6, 2, 6]
print(rolls.index(6))
print(rolls.count(6))
print(rolls.count(1))
if 1 in rolls:
    print(rolls.index(1))
else:
    print("no 1 rolled")

count() gives 0 for a missing value, but index() raises ValueError. Check with in first, as above.

See also: Sorting, List slicing, + and *.

Your turn

Sort times from fastest (smallest) to slowest in place. Then pop() the slowest time, and print it, the remaining list, and how many times are 12.

times = [14, 12, 19, 12, 11]
# add four lines: sort, pop the slowest, then print it, times, and the count of 12

Expected output

19
[11, 12, 12, 14]
2