Python lesson 8
Loops with Lists
Visit every item in a list. Automatically, one by one!
Loop Through a List
Combine a for loop with a list and Python visits every item automatically. Write what you want to do with each item. The loop handles the rest, no matter how long the list is!
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit) → apple banana mango
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Adding As You Go
scores = [10, 20, 30]
total = 0
for score in scores:
total = total + score
print(total)
Print Every Item
Click Run to loop through a list and print each item on its own line!
Hint: Click Run! The loop visits each planet in the list one by one.
planets = ["Mercury", "Venus", "Earth", "Mars"]
for planet in planets:
print(planet)
Your Favorites
Change the items to YOUR three favorite things and run the loop!
Hint: Change "coding", "pizza", "music" to three things you love and click Run!
favorites = ["coding", "pizza", "music"]
for item in favorites:
print(item)
Loop with If
Run this to print only the short words. Then add more words to the list!
Hint: The if checks the length of each word. Add more words to the list and run again!
words = ["hi", "elephant", "go", "python", "ok"]
for word in words:
if len(word) <= 3:
print(word, "is short")
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.