Python for loop

The for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range). Unlike traditional for loops in other programming languages, Python’s for loop doesn’t require an explicit counter variable.

Example

# Iterating through a list

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

for fruit in fruits:

    print(fruit)

Output:

apple

banana

cherry

Syntax

for variable in sequence:

    # Code to execute for each item in the sequence
  • variable: A temporary variable that takes the value of each item in the sequence during iteration.
  • sequence: A collection of items (e.g., list, tuple, string, range, etc.) over which the loop iterates.

Why Use for?

  1. Simple and Readable: Python’s for loop is straightforward and easy to understand.
  2. No Explicit Counter: The loop takes care of iteration automatically, reducing boilerplate code.
  3. Versatile: Can iterate over any iterable object, such as lists, dictionaries, sets, strings, and even custom objects.
  4. Powerful Features: Combined with functions like enumerate() and zip(), it becomes even more powerful for complex iterations.

Common Scenarios

1. Iterating Through a List

Iterate through items in a list.

numbers = [1, 2, 3, 4]

for num in numbers:

    print(num)

Output

1

2

3

4

2. Iterating Through a String

Iterate through each character in a string.

text = "Python"

for char in text:

    print(char)

Output

P

y

t

h

o

n

3. Using range()

Generate a sequence of numbers to iterate through.

for i in range(5):  # Generates numbers 0 to 4

    print(i)

Output

0

1

2

3

4

4. Iterating Through a Dictionary

Iterate over keys, values, or key-value pairs in a dictionary.

person = {"name": "Alice", "age": 25}

for key, value in person.items():

    print(f"{key}: {value}")

Output

name: Alice

age: 25

5. Using enumerate()

Get both the index and the item while iterating.

colors = ["red", "blue", "green"]

for index, color in enumerate(colors):

    print(f"{index}: {color}")

Output

0: red

1: blue

2: green

6. Nested for Loops

Iterate through nested structures.

matrix = [[1, 2], [3, 4], [5, 6]]

for row in matrix:

    for element in row:

        print(element)

Output

1

2

3

4

5

6

Example of for-else

for num in range(5):

    if num == 3:

        break

else:

    print("Completed without break")

In this example, the else block does not execute because the loop is interrupted by break.


Best Practices

  1. Keep It Simple: Avoid overcomplicating loops with excessive logic inside the body.
  2. Use break and continue Sparingly: Use these controls judiciously to avoid confusing behavior.
  3. Prefer for over while: Use for when iterating over a known sequence.

By mastering Python’s for loop, you can write cleaner and more efficient code for a wide range of scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top