Yandex

Python For Loop
Examples



A for loop in Python allows you to iterate over a sequence—like a list, string, tuple, or range — and execute a block of code for each item in that sequence. Unlike traditional C-style for-loops, Python takes a more readable and elegant approach.

Basic Syntax

for variable in sequence:
    # block of code

Here, variable takes the value of each item in sequence, one by one, and executes the indented block.

Example 1: Looping Over a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Each item in the list is printed on a new line. The loop automatically stops after the last element.

Example 2: Using Range with For Loop

for i in range(5):
    print("Step", i)

Output:

Step 0
Step 1
Step 2
Step 3
Step 4

range(5) generates numbers from 0 to 4. If you need to include 5, use range(6). Reference: range() bulitin function.

Example 3: Looping Through a String

for char in "Python":
    print(char)

Output:

P
y
t
h
o
n

Strings are iterable in Python—each character is treated as an element in the sequence.

Example 4: Using range(start, stop, step)

for i in range(2, 10, 2):
    print(i)

Output:

2
4
6
8

This version of range lets you control the start, stop, and increment values. It’s great for custom numeric patterns.

Example 5: Loop with else Clause

for i in range(3):
    print("Counting", i)
else:
    print("Loop finished!")

Output:

Counting 0
Counting 1
Counting 2
Loop finished!

The else clause runs after the loop completes normally. It’s skipped if the loop is exited via break.

Example 6: Nested For Loop

for i in range(2):
    for j in range(2):
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1

Nested loops let you work with multidimensional data or matrix-style problems.

Example 7: Breaking a Loop

for num in range(10):
    if num == 5:
        break
    print(num)

Output:

0
1
2
3
4

The loop stops when num equals 5. Use break carefully—it ends the loop prematurely.

Example 8: Skipping Iterations with continue

for num in range(5):
    if num == 2:
        continue
    print(num)

Output:

0
1
3
4

continue skips the current iteration and jumps to the next one.

Tips and Gotchas

  • Always check indentation. Python uses indentation to define loop blocks.
  • Modifying the sequence you're iterating over can lead to unpredictable behavior.
  • Use range(len(list)) only if you need index values. Otherwise, loop directly over items.
  • Prefer enumerate() if you need both index and item.

Example: Using enumerate()

names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
    print(index, name)

Output:

0 Alice
1 Bob
2 Charlie

When to Use For Loops

For loops shine when you know the number of iterations or are working with sequences. They're ideal for:

  • Traversing arrays, lists, or dictionaries
  • Running code a fixed number of times
  • Generating patterns or tables

Common Mistakes to Avoid

  • Forgetting the colon : after for statement
  • Using range() incorrectly (e.g., range(5, 2) returns nothing)
  • Confusing break with continue
  • Expecting a for loop to automatically loop over custom objects (you need to implement __iter__)

Conclusion

The for loop is your first step into controlling the flow of logic in Python. From iterating over simple lists to handling complex nested structures, mastering this loop opens the door to writing powerful and readable code. Take time to practice different examples and think of how you can apply this in real-world problems like data processing, filtering, or formatting outputs.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M