githubEdit

For Loops

Use for loops to iterate over sequences (lists, tuples, strings) and other iterables.

Syntax

for item in sequence:
    print(item)

Basic Example

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Using range()

range() generates numbers on demand, which is memory-efficient.

for i in range(5):
    print(i)

range(start, stop, step) is also supported:

print(list(range(2, 10, 2)))  # [2, 4, 6, 8]

Index + Value with enumerate()

for ... else

The else block runs only if the loop completes without a break.

Common Pitfalls

  • Modifying a list while iterating over it.

  • Using range(len(...)) when enumerate() is clearer.

Next | Previous

Last updated