5. For over a list
A for loop visits each element of a collection, one per pass:
itemis a name you choose; it holds the current element on each pass.collectionis an iterable: a list, a string, a dictionary view…- There is no counter to update. Python moves to the next element automatically, and the loop stops after the last one.
You already saw this syntax over a dictionary in chapter 7. Over a list, item takes each value in order:
Coming from JavaScript? for item in items is for...of, not for...in. for...in gives indexes; in Python indexes come from range(len(items)) or enumerate(items).
Print every fruit
Loop over fruits = ["apple", "banana", "cherry"] and print each fruit, one per line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add a label to each item
Loop over fruits = ["apple", "banana", "cherry"] and print each one as Fruit: <name> using an f-string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Double every number
Loop over numbers = [1, 2, 3, 4] and print each number multiplied by 2.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Print the length of each word
Loop over words = ["hi", "python", "code"] and print the length of each word with len().
Print exactly:
Create a free account to save your progress and unlock chapter 2.