0
0
Pythonprogramming~5 mins

Iterating over lists in Python

Choose your learning style9 modes available
Introduction

We use iteration to look at each item in a list one by one. This helps us do something with every item easily.

When you want to print all items in a shopping list.
When you need to add 1 to every number in a list of scores.
When you want to check if any item in a list matches a condition.
When you want to create a new list based on items from another list.
When you want to count how many items meet a certain rule.
Syntax
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.

Examples
This prints each fruit name on its own line.
Python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
When the list is empty, the loop does not run at all.
Python
numbers = []
for number in numbers:
    print(number)
Works fine even if the list has just one item.
Python
single_item_list = ['only']
for item in single_item_list:
    print(item)
You can check each item and do something only when a condition is true.
Python
colors = ['red', 'green', 'blue']
for color in colors:
    if color == 'green':
        print('Found green!')
Sample Program

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.

Python
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)
OutputSuccess
Important Notes

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.

Summary

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.