Skip to main content

How to Iterate Over a List Using For Loops in Python

How to Iterate Over a List Using For Loops in Python | Rustcode

How to Iterate Over a List Using For Loops in Python

Looping through a list is one of the most essential skills in Python for data processing, reporting, or automation. Python's for loop makes it easy and highly readable. Here are common ways to iterate over a list, with code examples and practical explanations.


Why Iterate Over a List?

  • Data Processing: Perform calculations, search, filter, or transform values.
  • Automation: Apply repeated actions to each item.
  • Reporting/Display: Print or collect results for users.

01. Direct Element Iteration (Recommended)

The simplest and most Pythonic way to use a for loop with a list is by looping over items directly:

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

Output:

red
green
blue
Explanation:
  • Each element from colors is assigned to color in each pass.
  • Use this for clean, readable code and whenever you don't need the index.

02. Iterating Using Index with range()

You can loop over indexes if you need to know positions or update elements:

numbers = [10, 20, 30]
for i in range(len(numbers)):
    print(f"Index {i}: {numbers[i]}")

Output:

Index 0: 10
Index 1: 20
Index 2: 30
Explanation:
  • range(len(numbers)) generates valid indexes for numbers.
  • Use this pattern if you need to access or modify the list by index.

03. Using enumerate() for Index and Value

The enumerate() function gives both index and value, and is the preferred way when you need both:

fruits = ["apple", "banana", "cherry"]
for idx, fruit in enumerate(fruits):
    print(f"At index {idx} is {fruit}")

Output:

At index 0 is apple
At index 1 is banana
At index 2 is cherry
Explanation:
  • enumerate(fruits) returns index and item as a pair.
  • Improves readability and reduces indexing errors.

04. List Comprehension for Iteration and Action

List comprehensions let you produce new lists or perform operations in a compact form:

numbers = [1, 2, 3, 4]
squares = [n ** 2 for n in numbers]
print(squares)

Output:

[1, 4, 9, 16]
Explanation:
  • Short way to apply a transformation or filter to every element in a list.
  • Use if you need a new list as a result.

05. Comparison Table: List Iteration Methods

Method Access Index Modify List Best For
for item in list No No Simple read/process
for i in range(len(list)) Yes Yes Change in-place/access index
for i, item in enumerate(list) Yes Yes Need both index and value
List comprehension No/limited No Create new lists

Conclusion

Iterating over a list with a for loop is a cornerstone of Python programming. Use direct iteration when you just need the values, range() or enumerate() when you need the index, and comprehensions for producing new lists. Mastering these patterns will help you write clean, Pythonic, and maintainable code.

Comments