0
0
PythonHow-ToBeginner · 3 min read

How to Iterate Over a List in Python: Simple Guide

To iterate over a list in Python, use a for loop that goes through each item one by one. The syntax is for item in list: followed by the code to run for each item.
📐

Syntax

The basic syntax to iterate over a list uses a for loop. You write for item in list: where item is a temporary variable holding each element, and list is the list you want to loop through. Inside the loop, you can use item to work with each element.

python
my_list = [1, 2, 3]
for item in my_list:
    print(item)
Output
1 2 3
💻

Example

This example shows how to print each element in a list of fruits. It demonstrates the simple for loop to access each item.

python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
Output
apple banana cherry
⚠️

Common Pitfalls

One common mistake is modifying the list while iterating over it, which can cause unexpected behavior. Another is forgetting the colon : after the for statement or incorrect indentation. Also, using the wrong variable name inside the loop can cause errors.

python
numbers = [1, 2, 3]
# Wrong: modifying list while iterating
for num in numbers:
    if num == 2:
        numbers.remove(num)  # This can skip elements

# Right: iterate over a copy to modify original
for num in numbers[:]:
    if num == 2:
        numbers.remove(num)
print(numbers)
Output
[1, 3]
📊

Quick Reference

  • for item in list: Loop through each item.
  • Use indentation to define the loop body.
  • Do not modify the list while looping directly.
  • Use descriptive variable names for clarity.

Key Takeaways

Use a for loop with the syntax 'for item in list:' to iterate over list elements.
Indent the code inside the loop to run it for each item.
Avoid changing the list while iterating over it directly to prevent bugs.
Choose clear variable names to make your code easy to read.
Remember the colon ':' after the for statement and proper indentation.