The Problem with Variables
Variables are great for storing one thing.
name = "Sam"
But what if you want to invite 20 friends to a party?
Use 20 variables?
friend1 = "Sam"
friend2 = "Alex"
friend3 = "Lee"
…
That is messy!
Enter the List
A List is a variable that can hold many things. It uses square brackets [].
friends = ["Sam", "Alex", "Lee", "Kim"]
Now we have one box (friends) containing four names.
Finding Things in the Box (Indexing)
How do we get “Sam” out of the box? We use the position number (index).
Important Rule: Computers start counting at 0.
| Sam | Alex | Lee | Kim |
|---|---|---|---|
| 0 | 1 | 2 | 3 |
print(friends[0]) # Prints "Sam"
print(friends[2]) # Prints "Lee"
Making Changes
Lists can change!
Adding Items
friends.append("Jo")
Now the list is: ["Sam", "Alex", "Lee", "Kim", "Jo"]
Changing Items
Oh no, “Alex” can’t come. “Max” is coming instead.
friends[1] = "Max"
Loops + Lists = Magic
Remember loops? They are best friends with lists.
for name in friends:
print("Hello", name)
Output:
Hello Sam
Hello Max
Hello Lee
Hello Kim
Hello Jo
This is how Instagram shows you 100 photos. It just loops through a list!
Try It Yourself
- Make a list of your 3 favorite foods.
- Print the first one.
- Print the last one.
This post is part of the Python Basics for Kids series, based on “Python for Kids from 8 to 88”.