Lists: Many Things at Once
Keep a whole collection under one name
So far each variable held one thing. But often we want a collection — a shopping list, a set of scores, names of friends. For that we use a list.
A list is written with square brackets, with items separated by commas:
fruits = ["apple", "banana", "cherry"]That one variable, fruits, now holds three strings.
Getting items out
Each item has a position number called an index. Here's the part that surprises everyone: counting starts at 0, not 1.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherrySo the first item is at index 0, the second at 1, and so on. It feels odd at first, then becomes second nature.
How many items?
len counts the items in a list, just like it counted characters in a string:
print(len(fruits)) # 3Adding to a list
You can add a new item to the end with .append():
fruits.append("date")
print(fruits) # ['apple', 'banana', 'cherry', 'date']Tip: Asking for an index that doesn't exist (like fruits[10] when there are only 3 items) gives an IndexError. Remember: the last valid index is always one less than the length.
Your turn
Add another fruit to the list with .append(), then print the whole list.
Press “Run code” to see the result.
Quick check
Q1 Given fruits = ["apple", "banana", "cherry"] , what does fruits[0] give?
Q2 What does fruits.append("date") do?
Want to save your progress? It's free.
Create a free account