Introduction

In Python, a for loop iterates over a sequence like a list, tuple, dictionary, set, or string. It simplifies repetitive tasks and enables you to execute a block of code for every element in the sequence. Python's for loop is widely used because of its readability and flexibility in handling iterations.

This guide shows you how to use Python for loops.

Prerequisites

To follow along with this guide:

  • Deploy a VPS server. For instance, Ubuntu 24.04.
  • Create a non-root sudo user set up.
  • Install Python.

Basic Syntax of Python for Loops

A for loop iterates over a sequence and processes a block of code for each element in the sequence. Here's the basic syntax:

Python
for item in sequence:
    # code block to process item

Example:

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

for number in numbers:
    print(number)

The above example outputs:

1
2
3
4
5

Use for Loops with Strings

You can use a for loop to iterate over characters in a string as follows.

Python
text = "Python"

for char in text:
    print(char)

Output:

P
y
t
h
o
n

This is particularly useful when working with string manipulation tasks.


Use for Loops with the range() Function

The range() function generates a sequence of numbers and you can use it with for loops. It allows you to specify a start, stop, and step value.

Example:

Python
for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

You can also skip numbers by changing the step value:

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

Output:

0
2
4
6
8

Nested for Loops

A nested for loop is a loop inside another loop. This looping structure is useful for tasks like working with matrices or nested structures.

Example:

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

for row in matrix:
    for number in row:
        print(number)

Output:

1
2
3
4
5
6

Implement Python for Loop Best Practices

To use for loops effectively, follow these best practices:

  • Use descriptive variable names: Helps make your code more readable.
  • Avoid unnecessary loops: Minimize the number of loops to improve performance.
  • Utilize built-in functions: Use functions like enumerate() and zip() to simplify complex iterations.
  • Keep loops concise: Avoid writing too much logic within a single loop.
  • Break out early when possible: Use break to exit loops when the result is achieved.

Example of using enumerate():

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

for index, color in enumerate(colors):
    print(f"Index: {index}, Color: {color}")

Discover Python for Loop Practical Use Cases

Practical use cases for for loops include:

  • Iterating over files: Process multiple files in a directory.
  • Data transformation: Apply operations to lists, such as squaring numbers.
  • Automation: Repeat tasks like sending emails or scraping websites.
  • Matrix operations: Work on 2D arrays or grids.
  • Data filtering: Filter and extract specific elements from sequences.

Example for data filtering:

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

# Extract only even numbers
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)

Output:

[2, 4]

Conclusion

Python for loops are a powerful for iterating over sequences. The looping structure lets you simplify repetitive tasks, work efficiently with data, and enhance code readability. In this guide, you learned the syntax, practical examples, and best practices for using for loops. Mastering the looping structure will boost your ability to write effective and optimized Python programs.