Unit 5 · Gotta Catch 'Em All! · Lesson 40 of 57
Listen Up
Listen up!
Say you want to store everyone on the CyberAcad team. You could do this:
person1 = "Karl"
person2 = "Amer"
person3 = "Zain"
person4 = "Alex"
person5 = "Rishabh"
That's already annoying, and we're only at 5. Now imagine 500.
Instead, you can put all of them in one list:
crew = ["Karl", "Amer", "Zain", "Alex", "Rishabh"]
A list is a bunch of values, in order, inside square brackets [], separated by commas. One variable, as many things as you want.
To grab one thing out of the list, put its position in square brackets after the name. Let's grab the second person on the team.
Before you run it: who do you think it'll print?
Run it!
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Question
Answer it in the lesson and it is checked as soon as you send it. Create a free account to do this part.
Counting from 0
The position of something in a list is called its index, and indexes start at 0:
So the first thing is crew[0], and the last thing is crew[4]. Ask for crew[5] and Python throws an IndexError, because there's nothing there.
A few more tricks:
print(crew[-1]) # Rishabh, -1 means the last one
print(len(crew)) # 5, len works on lists too!
crew.append("Doug") # add Doug to the end
print(crew)
Rishabh
5
['Karl', 'Amer', 'Zain', 'Alex', 'Rishabh', 'Doug']
.append() sticks something on the end of the list. (We'll talk about what that . means later. For now, just know that it works.)
You can also change something that's already in the list:
crew[3] = "Not Alex"
Alex is going to be mad about that one.
Here's a list of some of the most common passwords in the world. (Yes, people really use these.)
Print these 3 things, each on its own line:
- The first password in the list
- The last password in the list
- How many passwords are in the list
Then add amer123 to the end of the list (it belongs there), and print how many there are now.
So 4 lines in total. Don't count them yourself, make Python do it!
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.