A list method is a small tool that belongs to every list. You call it with a dot: bag.append("key"). Python has about a dozen of them, and you will use six or seven every day. This guide shows each one with a game example, plus the one trap that catches almost every beginner.
New to lists? Read Python lists for beginners first, then come back.
ADDING ITEMS: APPEND, INSERT, EXTEND
bag = ["sword"]
bag.append("potion")
bag.insert(0, "map")
bag.extend(["gem", "key"])
print(bag)['map', 'sword', 'potion', 'gem', 'key']
append(x)adds one item to the end.insert(i, x)puts an item at position i and pushes the rest to the right.insert(0, x)adds to the front.extend(other)adds every item of another list to the end.
The difference between append and extend matters. append adds the whole list as one item:
a = [1, 2]
a.append([3, 4])
print(a, len(a))
b = [1, 2]
b.extend([3, 4])
print(b, len(b))[1, 2, [3, 4]] 3
[1, 2, 3, 4] 4
REMOVING ITEMS: REMOVE, POP, CLEAR
remove(x) deletes the first item that equals x. You say what to remove.
enemies = ["bat", "slime", "bat"]
enemies.remove("bat")
print(enemies)['slime', 'bat']
pop() takes the last item out and gives it back to you, so you can use it. pop(i) does the same for position i. You say where to remove.
deck = ["ace", "king", "queen"]
top = deck.pop()
first = deck.pop(0)
print(top, first)
print(deck)queen ace
['king']
clear() empties the whole list in one go:
trail = [1, 2, 3]
trail.clear()
print(trail, len(trail))[] 0
pop when you know the position (or want the last one), remove when you know the value.q = ["a", "b", "c", "d"]
x = q.pop(1)
q.append(x)
print(q)pop(1) takes out "b" (index 1, the second item) and returns it. append then puts it at the end.FINDING THINGS: INDEX, COUNT AND IN
rolls = [3, 6, 2, 6, 6, 1]
print(rolls.count(6))
print(rolls.index(6))
print(5 in rolls)3
1
False
count(x)says how many times x appears.index(x)gives the position of the first x.inis not a method, but it is the safe way to ask "is it there?" before you callindexorremove.
SORTING: SORT() AND SORTED()
sort() puts the list in order in place. Numbers go smallest first, words go A to Z.
scores = [40, 15, 90, 15]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)[15, 15, 40, 90]
[90, 40, 15, 15]
sorted() is a function, not a method. It leaves the original alone and gives you a new sorted list:
names = ["Mia", "ana", "Bo"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(names)['Bo', 'Mia', 'ana']
['ana', 'Bo', 'Mia']
['Mia', 'ana', 'Bo']
Capital letters sort before small ones, so key=str.lower compares the words as if they were all lowercase. You can sort by any rule: key=len sorts words by length.
words = ["snake", "go", "python", "run"]
words.sort(key=len)
print(words)['go', 'run', 'snake', 'python']
reverse() simply flips the order, without sorting:
path = ["start", "cave", "boss"]
path.reverse()
print(path)['boss', 'cave', 'start']
THE BIG TRAP: METHODS THAT RETURN NONE
Methods that change the list (append, insert, extend, remove, sort, reverse, clear) give back None. So this looks right but loses your list:
scores = [3, 1, 2]
scores = scores.sort()
print(scores)None
Either call the method on its own line, or use sorted() when you want a result to store:
scores = [3, 1, 2]
scores.sort()
print(scores)
top = sorted([3, 1, 2], reverse=True)
print(top[0])[1, 2, 3]
3
Only pop, index and count give you a useful value back.
a = [5, 2, 8]
b = sorted(a)
a.reverse()
print(a[0], b[0])sorted(a) makes a new list [2, 5, 8], so b[0] is 2. a is untouched until reverse() flips it to [8, 2, 5], so a[0] is 8.QUICK CHEAT SHEET
- Add:
append(x)·insert(i, x)·extend(list) - Remove:
remove(x)·pop()·pop(i)·clear() - Find:
index(x)·count(x)·x in list - Order:
sort()·sort(reverse=True)·sort(key=len)·reverse()·sorted(list) - Copy:
copy()gives a separate list, so changing one does not change the other.
COMMON BEGINNER MISTAKES
x = x.sort(). sort changes the list and returns None. Write x.sort(), or y = sorted(x).bag.remove("gem") crashes with ValueError if there is no gem. Check with if "gem" in bag: first.[].pop() raises IndexError: pop from empty list. Check if bag: before you pop.a.append([3, 4]) adds one item that is a list. Use extend to add the items one by one.[3, "a"].sort() raises TypeError, because Python cannot say whether 3 comes before "a".bag = ["sword"]
bag.remove("gem")
# ValueError: list.remove(x): x not in list
WHAT NEXT?
Want to build lists in one line? Try list comprehensions. Curious how insert(0, ...) and pop() move a snake across the board? The Snake game logic guide uses exactly these two methods.
PRACTICE IT, DON'T JUST READ IT
Loop Lagoon in Snekcade has you fill, sort and empty lists in short swipes, ending with a loot counter you build yourself. It is one of the two free worlds.
PLAY LOOP LAGOON ▸FAQ
What is the difference between sort() and sorted() in Python?
list.sort() changes the list itself and returns None. sorted(list) leaves the original alone and returns a new sorted list.
Why does my list become None after sort()?
Because you wrote x = x.sort(). sort() changes the list in place and returns None, so x is replaced by None. Write x.sort() on its own line instead.
What is the difference between append and extend?
append adds one item to the end, even if that item is a list. extend adds every item of another list to the end, one by one.
What is the difference between pop and remove?
pop removes by position (the last item if you give no index) and returns the item. remove deletes the first item with a given value and returns None.