Unit 5 · Gotta Catch 'Em All! · Lesson 41 of 57
Loop the List
Loop the list
Remember how a for loop can go through a string letter by letter? It works on lists too, one thing at a time:
crew = ["Karl", "Amer", "Zain", "Alex", "Rishabh"]
for person in crew:
print(f"Hi, {person}!")
Hi, Karl!
Hi, Amer!
Hi, Zain!
Hi, Alex!
Hi, Rishabh!
Each time around, the next thing in the list gets stored in person.
Is it in there?
in works on lists too. It asks "is this somewhere in the list?"
admins = ["karl", "zain"]
print("karl" in admins)
print("alex" in admins)
True
False
(Alex has asked to be an admin 14 times. The answer is still no.)
Building a new list
Combine a loop, an if, and .append(), and you can pick things out of one list and put them into another:
scores = [95, 42, 88, 61, 100]
passed = []
for score in scores:
if score >= 70:
passed.append(score)
print(passed)
[95, 88, 100]
passed = [] is an empty list. It starts with nothing in it, and the loop fills it up.
Zain is auditing everyone's passwords. (Don't worry, they're fake.)
Make a function called too_short that takes a list of passwords and returns a new list of only the passwords that are shorter than 8 characters.
too_short(["amer123", "purple4life", "cat"])
should give back ["amer123", "cat"].
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.