TExcelTAD
Home › Python › Python List Methods

Python List Methods

Lists have a set of built-in methods for adding, removing, searching and ordering items. Unlike string methods, most list methods modify the list in place and return None.

Overview

Method What it does
append(x) Add x to the end
extend(iterable) Add every item from another iterable
insert(i, x) Insert x before position i
remove(x) Remove the first item equal to x
pop([i]) Remove and return the item at i (last by default)
clear() Remove all items
index(x) Position of the first x
count(x) How many times x appears
sort() Sort the list in place
reverse() Reverse the list in place
copy() Return a shallow copy

Adding items

python · try it yourself
queue = ["Ann", "Binh"]
queue.append("Chi")
print(queue)

queue.insert(0, "VIP")
print(queue)

queue.extend(["Dung", "Em"])
print(queue)
['Ann', 'Binh', 'Chi']
['VIP', 'Ann', 'Binh', 'Chi']
['VIP', 'Ann', 'Binh', 'Chi', 'Dung', 'Em']

A frequent mistake is using append when you meant extend: append([1, 2]) adds one item, the list [1, 2].

python · try it yourself
a = [0]
a.append([1, 2])
b = [0]
b.extend([1, 2])
print(a, b)
[0, [1, 2]] [0, 1, 2]

Removing items

python · try it yourself
stack = ["a", "b", "c", "d", "b"]

stack.remove("b")          # first matching value
print(stack)

last = stack.pop()         # remove and return the last item
print(last, stack)

first = stack.pop(0)       # remove and return by index
print(first, stack)

del stack[0]               # the del statement also works
print(stack)

stack.clear()
print(stack)
['a', 'c', 'd', 'b']
b ['a', 'c', 'd']
a ['c', 'd']
['d']
[]

remove() raises ValueError if the value isn't present, and pop() raises IndexError on an empty list — check with in or if stack: first.

Sorting

sort() orders the list in place. sorted() is a built-in function that leaves the original alone and returns a new sorted list.

python · try it yourself
scores = [70, 95, 82, 61]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)

names = ["bob", "Alice", "carol", "Dave"]
print(sorted(names))                    # uppercase sorts before lowercase
print(sorted(names, key=str.lower))     # case-insensitive
print(sorted(names, key=len))           # by length (ties keep their order)
print(names)                            # unchanged
[61, 70, 82, 95]
[95, 82, 70, 61]
['Alice', 'Dave', 'bob', 'carol']
['Alice', 'bob', 'carol', 'Dave']
['bob', 'Dave', 'Alice', 'carol']
['bob', 'Alice', 'carol', 'Dave']

The key argument takes a function that is applied to each item to decide its sort position. Python's sort is stable, which means items with equal keys stay in their original order.

Sorting records

key really shines with structured data:

python · try it yourself
people = [("Hoa", 31), ("An", 25), ("Quang", 40)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
oldest = max(people, key=lambda p: p[1])
print(oldest[0])
[('An', 25), ('Hoa', 31), ('Quang', 40)]
Quang

Searching and counting

python · try it yourself
votes = ["yes", "no", "yes", "yes", "abstain"]
print(votes.count("yes"))
print(votes.index("no"))
print("maybe" in votes)
votes.reverse()
print(votes)
3
1
False
['abstain', 'yes', 'yes', 'no', 'yes']

Tip: A very common bug: numbers = numbers.sort(). Because sort() returns None, this throws away your list. Either call numbers.sort() on its own line, or use numbers = sorted(numbers).

Test yourself

What does pop() return?

  1. Nothing (None)
  2. The removed item
  3. The new length
  4. The remaining list

What is the difference between list.sort() and sorted(list)?

  1. No difference
  2. sort() changes the list in place and returns None; sorted() returns a new list
  3. sorted() only works on numbers
  4. sort() returns a new list

After x = [1]; x.append([2, 3]), what is len(x)?

  1. 1
  2. 2
  3. 3
  4. 4