Loop Lists
Iteration Techniques
Python provides multiple ways to loop through lists. You can use simple for loops, enumerate() for index-value pairs, zip() for parallel iteration, comprehensions for inline creation, or functional tools like map() and filter().
Example
fruits = ['apple', 'banana', 'cherry']
# Basic iteration
for fruit in fruits:
print(fruit.upper())
# With index using enumerate
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Parallel iteration with zip
prices = [1.2, 0.5, 2.3]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ${price}")
Output
APPLE BANANA CHERRY 0: apple 1: banana 2: cherry apple: $1.2 banana: $0.5 cherry: $2.3
Performance Patterns
All common looping styles are efficient, but they have slightly different overhead. Simple for loops are fastest, while enumerate() adds minimal overhead for index-value pairs. Iterating with range(len()) is less idiomatic but sometimes needed when modifying elements by index.
Example
from timeit import timeit
setup = "lst = list(range(1000))"
print("Simple loop:", timeit("for x in lst: pass", setup))
print("Enumerate:", timeit("for i,x in enumerate(lst): pass", setup))
print("Range len:", timeit("for i in range(len(lst)): lst[i]", setup))
ℹ️ Note: Prefer simple iteration for readability and performance. Use enumerate() when both index and value are required.
Advanced Iteration
You can refine iteration using reversed(), slicing, or generator expressions with conditions. These approaches give more control over traversal order and filtering.
Example
# Reversed iteration
for fruit in reversed(fruits):
print(fruit)
# Sliced iteration (skip first element)
for fruit in fruits[1:]:
print(fruit)
# Conditional iteration (only fruits with 'a')
for fruit in (f for f in fruits if 'a' in f):
print(fruit)
Output
cherry banana apple banana cherry apple banana