Lists hold many things
A list stores several values in order, inside square brackets:
games = ["Minecraft", "Tetris", "Celeste"]
Lists work a lot like strings: games[0] is the first item, games[-1] the last, len(games) the count, and slicing works the same way. You can loop over a list with for game in games:, and check membership with "Tetris" in games.
The big difference: lists are mutable. You can change them in place.
games.append("Hades")adds to the end.games.insert(0, "Pong")adds at a position.games.remove("Tetris")removes the first matching value.games.pop()removes and returns the last item.games[1] = "Portal"replaces an item.
Notice that append and friends change the list and return None. So games = games.append("x") is a classic bug: you just replaced your list with None.
Sorting has two flavours. games.sort() sorts the list itself and returns None. sorted(games) leaves the original alone and gives you a new sorted list. For numbers, sum(nums), min(nums) and max(nums) do what their names say.
Remember the name tag idea from the variables lesson? Here it finally matters:
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
b = a did not copy the list. Both names point at the same list, so changing it through b shows up through a too. If you want a real copy, use b = a.copy() or b = a[:].
Try it yourself
Edit it. Break it. Run it again.games = ["Minecraft", "Tetris", "Celeste"]
games.append("Hades")
games.remove("Tetris")
print(games, len(games))
print(games[0], games[-1])
scores = [42, 7, 99, 13]
print(sorted(scores), "original:", scores)
print("sum", sum(scores), "max", max(scores))
a = [1, 2, 3]
b = a # same list, two names
c = a.copy() # a real copy
b.append(4)
print(a, c)
Your turn
Type it yourself. That is the whole trick.1Shopping list
Start from the list given. Add "milk" to the end, remove "crisps", then print the list. The output should be exactly ['bread', 'eggs', 'milk'].
shopping = ["bread", "crisps", "eggs"] print(shopping)
2Only the big ones
Build a new list called big that contains only the numbers from nums that are greater than 10, in the same order, then print big. The output should be [12, 45, 11].
nums = [3, 12, 7, 45, 10, 11] big = [] print(nums)