Python Lists for Beginners: append, len and Indexing Explained
A list holds many values in one variable. Instead of monster1, monster2, monster3, you keep a whole team together.
Making a list
team = ["Pyrocub", "Pengpip", "Bellbun"]
print(team)
Square brackets, items separated by commas.
Reading one item: indexing
print(team[0]) # Pyrocub
print(team[2]) # Bellbun
print(team[-1]) # Bellbun (last item)
Python counts from 0, so the first item is team[0]. Negative numbers count from the end.
How many items: len()
print(len(team)) # 3
Adding items: append()
team.append("Surgator")
print(team) # four monsters now
print(len(team)) # 4
Changing an item
team[1] = "Bristusk"
Looping through a list
for monster in team:
print(monster, "is ready")
The most common error: IndexError
IndexError: list index out of range
This means you asked for a position that does not exist. With three items, the valid indexes are 0, 1 and 2. Asking for team[3] fails. A handy check: the last valid index is always len(team) - 1.
Mini challenge
Start with an empty list bag = [], append three items, then print how many items are in the bag and what the first one is.
The lists, append and len and list index lessons let you practise this step by step with instant feedback.