the full guide

List methods reference

List methods are functions attached to every list. They add, remove, find, count, sort and copy items. Most of them change the list in place and return None.

6 min Intermediate

What you need: The earlier topics of this module.

Definition

List methods are functions attached to every list. They add, remove, find, count, sort and copy items. Most of them change the list in place and return None.

In simple words

Think of a list as a shopping list you can edit. append adds to the end, remove crosses out an item, and sort puts it in order. The list itself changes, so no new list comes back.

Why it matters

Lists are everywhere, so knowing these saves a lot of hand-written loops.

How it works

MethodDoesReturns
append(x)Adds x at the endNone
extend(list)Adds all items of another listNone
insert(i, x)Inserts x at position iNone
remove(x)Removes the first x, error if absentNone
pop(i)Removes and returns an item (the last by default)The item
clear()Empties the listNone
index(x)Position of the first xint
count(x)How many times x appearsint
sort()Sorts in placeNone
reverse()Reverses in placeNone
copy()A shallow copyA new list

In code

list_methods.py
items = ["pen", "book"]
items.append("bag")
items.insert(0, "pencil")
items.extend(["ruler", "pen"])
print(items)

print("Last:", items.pop())
print("Count of pen:", items.count("pen"))
print("Index of book:", items.index("book"))

items.sort()
print(items)
print("sort() returns:", items.sort())

Output

['pencil', 'pen', 'book', 'bag', 'ruler', 'pen']
Last: pen
Count of pen: 1
Index of book: 2
['bag', 'book', 'pen', 'pencil', 'ruler']
sort() returns: None

Common mistakes

  • Writing x = x.sort(). sort returns None, so x is lost. Use sorted(x) to get a new list.
  • Using append with a list when you meant extend. append adds the whole list as one item.

Check yourself

Question 1

1. x = [1, 2]; x.append([3]). What is x?

Question 2

2. Which method returns the removed item?

Summary

  • Most list methods change the list and return None.
  • sort() changes in place, and sorted() gives a new list.

Finished reading?

Sources: The Python Tutorial, python.org