3. Lists
A list holds lots of values in one box, in order. In your evolution sim you’ll keep all your creatures in a list, and all your food in another list.
Making a list
Use square brackets [ ], with commas between the items.
Output:
A list can hold numbers too:
An empty list
Often you start with an empty list and fill it up later:
Adding to a list
Use .append() to add one item onto the end.
Output:
How long is the list?
len() tells you how many items are in a list.
Output:
This is handy: len(creatures) is how many creatures are alive right now.
Getting one item — indexes
Each item has a position number called its index. The tricky part: indexes start at 0, not 1.
Get an item with square brackets and its index:
Output:
You can also count from the end using negative numbers. -1 is the last item:
Output:
Changing an item
Put a new value into a position:
Output:
Removing from a list
.remove() takes out the first item that matches the value you give it:
Output:
.pop() removes an item by its index and hands it back to you:
Output:
Is something in the list?
The word in checks whether a value is somewhere in the list. It gives back True or False.
Output:
Going through every item (the for loop)
This is one of the most useful things in all of programming. A for loop lets you do something to every item in a list, one at a time.
Output:
Read it out loud: “for each name in the list of creature names, print a message.” The word name is a temporary box that holds one item each time round the loop. You can call it whatever makes sense — for creature in creatures, for food in food_items, and so on.
There’s a whole page on loops next — 4. Loops — this was just a taste.
✅ Quick recap
- Make a list with
[ ]:creatures = ["Spike", "Pip"] - Add with
.append("Bramble") - Count with
len(creatures) - Get an item with its index (starting at 0):
creatures[0] - Change an item:
creatures[0] = "Spike" - Remove with
.remove("Spike")or.pop(0) - Check with
if "Spike" in creatures: - Go through every item with
for creature in creatures: