We use iteration to look at each item in a list one by one. This helps us do something with every item easily.
Iterating over lists in Python
my_list = ['item1', 'item2', 'item3'] for item in my_list: # do something with item
The for loop goes through each item in the list one by one.
Indentation (spaces before the code inside the loop) is important in Python.
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
numbers = [] for number in numbers: print(number)
single_item_list = ['only'] for item in single_item_list: print(item)
colors = ['red', 'green', 'blue'] for color in colors: if color == 'green': print('Found green!')
This program defines a function to print all items in a list with a dash before each. Then it calls the function with a shopping list.
def print_list_items(items): print('List has', len(items), 'items:') for item in items: print('-', item) shopping_list = ['milk', 'eggs', 'bread'] print_list_items(shopping_list)
Time complexity is O(n) because it looks at each item once.
Space complexity is O(1) if you only print or use items one by one.
Common mistake: forgetting to indent the code inside the loop, which causes errors.
Use iteration when you want to do something with every item. Use list comprehensions if you want to create a new list quickly.
Iteration lets you visit each item in a list one at a time.
Use a for loop with a list to do this simply.
Works with empty lists and lists of any size.