A variable holds one thing. But what if you want to keep track of five favourite foods, ten high scores, or every player in a game? Making a new variable for each would be exhausting. A list solves this by holding many values under a single name.
Making a list
snacks = ["apple", "popcorn", "grapes"]
print(snacks)The square brackets [ ] mark the list, and commas separate the items. Strings need quote marks; numbers do not:
scores = [10, 25, 7]Getting one item out
Each item has a position number called an index. The surprise: Python starts counting at 0.
snacks = ["apple", "popcorn", "grapes"]
print(snacks[0])
print(snacks[2])That prints apple and then grapes. The first item is number 0, the second is number 1, and so on. Asking for snacks[3] gives an error, because there is no fourth item. That error is a great teacher: ask your child to predict it before running the code.
Changing a list
Lists can grow, shrink and change.
snacks.append("cheese")
snacks.remove("popcorn")
snacks[0] = "banana"
print(snacks)appendadds an item to the end.removetakes an item out by its value.- Assigning to an index replaces that item.
How many items?
print(len(snacks))len is short for "length" and tells you how many items the list holds.
Lists and loops are best friends
The real power appears when you combine a list with a loop, which is covered in Python loops for kids:
for snack in snacks:
print("I would like some", snack)The loop visits every item, no matter how many there are. Add ten more snacks and the same three lines still work.
Try these challenges
- Make a list of your five favourite animals and print the third one.
- Add a new animal to the end, then print the whole list.
- Use a loop to print "I love" followed by each animal.
- Make a list of numbers and print how many there are.
- Ask the user to type a name, add it to a list of friends, and print the list.
Common stumbles
- Off-by-one confusion. If a list has 3 items, the last index is 2, not 3. This trips up adults too.
- Forgetting quotes around text items.
- Using round brackets by mistake. Square brackets make a list; round ones do something else.
Lists show up in nearly every real program: a playlist, a shopping basket, a leaderboard. When your child is comfortable here, the next natural step is functions, which let them name and reuse chunks of code. If they are still at the start of the journey, the Python course walks through variables, loops and lists one small step at a time.