Skip to content

The For Loop in Python: A Comprehensive Guide to Iterating Through Sequences

Updated: at 04:12 AM

The for loop is a fundamental concept in Python and programming in general. It allows you to iterate through sequence data types like lists, tuples, strings, and other iterables in Python. Mastering for loops can help you write cleaner and more efficient Python code.

In this comprehensive guide, we will cover everything you need to know about for loops in Python. We will look at the basic syntax and structure of for loops, how to loop through different data types, common pitfalls and best practices when using for loops, and more advanced techniques like nested loops and looping with enumerate. Real-world examples and sample code snippets are provided throughout to help illustrate the key concepts.

Table of Contents

Open Table of Contents

What is a For Loop?

A for loop allows you to execute a block of code repeatedly for each element in a sequence. This is useful when you need to perform the same operation on every item in a list, tuple, string, or other iterable object.

Here is the basic syntax of a for loop in Python:

for element in sequence:
    # code block to execute for each element

This loop will keep iterating until it reaches the end of the sequence. The power of the for loop comes from performing an operation on every element in a sequence automatically.

Looping Through a List

Lists are one of the most common sequence types to loop through in Python. Here is an example:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

This will print out each number in the list on a separate line:

1
2
3
4
5

We can also perform some calculation or operation on each element:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    squared = num ** 2
    print(squared)

This loops through and prints the square of each number:

1
4
9
16
25

The key thing to remember is that the for loop automatically iterates through the list, allowing you to focus on the task you want to perform on each element.

Looping Through a Tuple

Tuples are immutable sequences that work similarly to lists. To loop through a tuple, just reference the tuple instead of a list:

digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

for digit in digits:
    print(digit)

This will output each tuple element value.

Looping Through a String

You can also iterate through a string to process each character. Here’s an example:

name = "Python"

for letter in name:
    print(letter)

This will print each letter on a separate line:

P
y
t
h
o
n

Strings are iterable sequences, so you can loop through them just like lists and tuples.

Looping with the Range Function

Rather than explicitly defining a sequence to loop through, you can generate one on the fly using Python’s range() function.

range(n) generates a sequence of numbers from 0 to n-1. For example:

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

This prints the numbers 0 through 4.

You can also define a starting point and increment:

for i in range(3, 8):
    print(i)

# Prints 3, 4, 5, 6, 7

Using range() can be useful when you need to loop a certain number of times but don’t need an explicit list.

Accessing the Index during Iteration

Sometimes it’s useful to access the index of the current element during iteration. The built-in enumerate() function handles this:

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

for i, color in enumerate(colors):
    print(i, color)

This prints:

0 red
1 green
2 blue

enumerate() wraps the iterable and returns a tuple with an index counter and the value during each iteration.

Looping Backwards

To loop through a sequence in reverse order, you can combine range() and len():

numbers = [1, 2, 3, 4, 5]

for i in range(len(numbers) - 1, -1, -1):
    print(numbers[i])

This loops from the last index down to 0, printing the numbers in reverse order.

Looping Multiple Sequences Together

You can loop through multiple sequences together by zipping them:

names = ['Elwood', 'Jake']
last_names = ['Blues', 'Blues']

for first_name, last_name in zip(names, last_names):
    print(first_name, last_name)

This will loop through and print corresponding values from each list:

Elwood Blues
Jake Blues

Zipping works great when you need to iterate over multiple related sequences in parallel.

Exiting Early with break

You can exit out of a loop early without reaching the end by using the break statement:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        print('Found 3!')
        break

    print(num)

This will only print up to 3 before exiting the loop. The break statement immediately terminates the loop.

Skipping Iterations with continue

To skip the current iteration but keep the loop going, use continue:

for i in range(10):
    if i % 2 == 0:
        continue

    print(i)

This will print only the odd numbers, skipping even ones. The continue statement jumps back to the top of the loop early.

Looping Efficiently with Numpy Vectorization

Python loops can sometimes be slow for numerical computing. NumPy provides fast vectorized operations on arrays without requiring explicit loops:

import numpy as np

a = np.arange(5)
print(a) # [0 1 2 3 4]

a *= 2 # a = a * 2 broadcasts across array
print(a) # [0 2 4 6 8]

This applies the multiplication across the whole array in one step.

For/Else Clause

Python has a unique else clause for for loops that executes after the loop completes normally:

for i in range(5):
    print(i)
else:
    print('Loop completed')

The else block runs only if the loop finishes iterating through the sequence and did not hit break.

Common For Loop Patterns

Certain for loop patterns appear often in Python code:

Sum values in a sequence:

total = 0
for num in [1, 2, 3, 4, 5]:
    total += num

print(total) # 15

Find max/min value:

numbers = [1, 4, 2, 8, 3, 5]

min_num = numbers[0]
for num in numbers:
    if num < min_num:
        min_num = num

print(min_num) # 1

Filtering:

even_nums = []
for num in range(1, 11):
    if num % 2 == 0:
        even_nums.append(num)

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

These examples demonstrate common ways for loops are used on sequences.

Best Practices for For Loops

Here are some key best practices to follow when using for loops in Python:

Following these practices will help you write clean and maintainable for loops that are easy to understand.

Common For Loop Pitfalls

Here are some common mistakes and pitfalls when using for loops in Python:

Forgetting to Indent the Loop Body

The colon : after the for statement should be followed by an indented block of code to run each iteration. Forgetting to indent will cause an IndentationError.

Not Updating Variables Inside the Loop

If you need to update a variable or accumulator, make sure to reference it inside the loop. Simply initializing it outside the loop won’t automatically update it.

Infinite Loops

Failing to update loop variables or iterating over a sequence that never ends can lead to infinite loops that crash your program. Use Ctrl + C to force quit a runaway Python process.

Off-by-One Errors

Looping for i in range(len(sequence)) will loop from 0 to length - 1. This can lead to off-by-one errors if you expect to loop length times. Use range(1, len(sequence)+1) to loop 1 to length instead.

Modifying Lists During Iteration

Mutating a list while looping through it can have unexpected results. Make copies to avoid this issue.

Nested For Loops

For loops can be nested to perform nested iteration:

for num1 in range(5):
    for num2 in range(5):
        print(num1, num2)

This loops 25 times, iterating through both ranges fully.

Nested loops are powerful but can also be computationally expensive. Avoid going more than 2-3 levels deep when possible.

Conclusion

Iterating through sequences is a fundamental concept in Python. The for loop provides a simple but powerful way to process lists, tuples, strings, and other iterables element by element.

Mastering for loops allows you to write more scalable and maintainable Python code. By understanding how to leverage tools like range(), enumerate(), zip(), break and continue, you can iterate like a professional Python developer.

Following best practices like using descriptive names, keeping loop bodies small, and avoiding common pitfalls will help you deploy for loops effectively across your Python projects.