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
| Method | Does | Returns |
|---|---|---|
| append(x) | Adds x at the end | None |
| extend(list) | Adds all items of another list | None |
| insert(i, x) | Inserts x at position i | None |
| remove(x) | Removes the first x, error if absent | None |
| pop(i) | Removes and returns an item (the last by default) | The item |
| clear() | Empties the list | None |
| index(x) | Position of the first x | int |
| count(x) | How many times x appears | int |
| sort() | Sorts in place | None |
| reverse() | Reverses in place | None |
| copy() | A shallow copy | A new list |
In code
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
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