A list stores many values in one variable, in order. A shopping list, a high-score table, the cards in your hand: all lists.
MAKING A LIST
loot = ["sword", "shield", "potion"]
print(loot)
print(len(loot))['sword', 'shield', 'potion']
3
Square brackets, items separated by commas. len() tells you how many items there are.
GETTING ONE ITEM (INDEXING)
Every item has a position number called an index. Counting starts at 0, not 1.
loot = ["sword", "shield", "potion"]
print(loot[0])
print(loot[2])
print(loot[-1])sword
potion
potion
[-1] is always the last item.CHANGING A LIST
loot = ["sword", "shield"]
loot.append("potion")
loot[0] = "axe"
loot.remove("shield")
print(loot)['axe', 'potion']
append()adds to the end.list[i] = ...replaces an item.remove()deletes the first matching item.
SLICES: A PIECE OF THE LIST
nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])[20, 30]
[10, 20]
[1:3] means from index 1 up to, but not including, index 3. Just like range().
LOOPING OVER A LIST
scores = [7, 12, 5]
for s in scores:
print(s * 10)
print("Best:", max(scores))70
120
50
Best: 12
Useful helpers: max(), min(), sum(), sorted().
pets = ["cat", "dog", "fish"]
pets.append("snake")
print(pets[3])append the list has 4 items. Index 3 is the fourth one: snake.COMMON BEGINNER MISTAKES
[0]. A list of 3 items has indexes 0, 1 and 2.loot[3] in a list of 3 items crashes, because there is no fourth item.x = x.append(...). append changes the list itself and returns None. Just write x.append(...).nums = [3, 1, 2]
nums.sort()
print(nums[0] + nums[-1])[1, 2, 3]. The first item is 1 and the last is 3, so the answer is 4.PRACTICE IT, DON'T JUST READ IT
Lists are a big part of Loop Lagoon in Snekcade, ending with a loot counter you build yourself. It is one of the two free worlds.
PLAY LOOP LAGOON ▸FAQ
Why do Python lists start at 0?
The index is the distance from the start. The first item is 0 steps from the start, so it is index 0.
How do I get the last item of a list?
Use index -1, for example items[-1]. Negative indexes count from the end.
What is the difference between append and insert?
append adds one item to the end. insert(i, x) puts the item at position i.