By the end of this lesson, you will be able to efficiently loop through Python lists (arrays) using various iteration techniques, including direct access, index-based loops, and unpacking.
What it is
In Python, "arrays" are typically represented by list objects. Iterating over them means visiting each element sequentially to perform an action, such as printing, calculating, or modifying data. The mental model is a conveyor belt: you pick up one item at a time, process it, and move to the next. Related terms include iterables, indices, and unpacking.
Why it matters
- Data Processing: Essential for cleaning, transforming, or analyzing datasets stored in lists.
- Algorithm Implementation: Many algorithms (like sorting or searching) require examining every element.
- User Interface Updates: Used to render lists of items on a screen or console.
- File Handling: Often used to read lines from a file into a list and process them one by one.
Syntax or steps
The most common pattern is the for loop. You can iterate directly over elements or use indices if you need position information.
- Direct Iteration: Use
for item in my_list:when you only need the value. - Index Iteration: Use
for i in range(len(my_list)):when you need both the index and the value. - Enumerate: Use
for i, item in enumerate(my_list):for a cleaner way to get both index and value.
Example
# A simple list of scores
scores = [85, 90, 78, 92]
# 1. Direct iteration (best for just reading values)
print("All scores:")
for score in scores:
print(score)
# 2. Using enumerate (best for needing position + value)
print("\nScores with positions:")
for index, score in enumerate(scores):
print(f"Student {index}: Score {score}")
# 3. Modifying elements requires index access
print("\nAdding bonus points:")
for i in range(len(scores)):
scores[i] += 5
print(f"Updated Student {i}: {scores[i]}")
Explanation: The first loop simply prints each number. The second uses enumerate() to pair each score with its index automatically. The third loop uses range(len()) because we are modifying the original list; direct iteration cannot change the source list's structure or values effectively without creating new objects.
Common mistakes
- Modifying while iterating directly: Changing a list's size (adding/removing items) inside a
for item in list:loop causes unpredictable behavior. Fix: Iterate over a copy (list[:]) or use awhileloop with indices. - Using
range(len())unnecessarily: If you don't need the index, avoid it. It makes code harder to read. Fix: Use direct iteration orenumerate(). - Confusing tuples and lists: Remember that strings are also iterable. Looping over a string yields characters, not words. Fix: Use
.split()first if you want word-level iteration.
When to use it
| Method | Use When... |
|---|---|
for x in list |
You only need the values and won't modify the list structure. |
for i, x in enumerate(list) |
You need the index for labeling, logging, or conditional logic based on position. |
for i in range(len(list)) |
You need to modify the list elements in place or access neighboring elements via index math. |
Practice
Guided Exercise: Create a list of names ["Alice", "Bob", "Charlie"]. Write a loop that prints "Hello, [Name]!" for each person.
Challenge: Given numbers = [1, 2, 3, 4], write a loop that creates a new list containing the squares of these numbers using a list comprehension (an advanced iteration shortcut).
Hint for Challenge: [x**2 for x in numbers]
Quick check
Question: Why should you avoid using for i in range(len(my_list)): if you only need to print the values?
Answer: It is less readable and more verbose than for item in my_list:. Pythonic style prefers direct iteration unless the index is explicitly required.
Summary
Iterating over arrays in Python is fundamental for data manipulation. Choose direct iteration for simplicity, enumerate() when you need position context, and index-based loops only when modifying the list in place. Mastering these patterns leads to cleaner, more efficient code.