Skip to content

script_7.py - Iterate Through a List

Code

Python
#!/usr/bin/env python3
"""Iterate through a list"""

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

for fruit in fruits:
    print(f"I like {fruit}")

Explanation

Line 4: fruits = ["apple", "banana", "cherry", "date", "elderberry"] - fruits is a list type containing string elements - List is iterable (can be looped over) - Contains 5 elements

Line 6: for fruit in fruits: - Iterates directly over list elements (not indices) - fruit is loop variable that takes each list element in order - First iteration: fruit="apple", second: fruit="banana", etc. - Python automatically gets each element from the list - More Pythonic than using range(len(fruits)) - fruit is string type (same type as list elements) - Variable name is singular (fruit) while iterable is plural (fruits) - common convention

Line 7: print(f"I like {fruit}") - fruit variable contains current element - Executes 5 times (once per list element)