Python Tutorial

Python for Loop: Syntax, Examples, How to Use for loop?

Table of Contents

  • Introduction
  • What is for Loop in Python?
  • For loop Syntax in Python
  • Iterable in for Loop in Python
  • How Does for Loop Work in Python?
  • Examples of ‘for’ loops in Python
  • How to Use for loop in Python?
  • range() Function for Numerical Iterations in for loop
  • Use of Loop Control Statements in Python
  • Nested for Loops in Python
  • List Comprehensions Using for loop in Python
  • Uses of for Loops in Python
  • Best Practices to Write Efficient and Readable 'for' loops in Python
  • Python for loop Programs
  • QUIZ!

Introduction

Repetitive tasks are a common occurrence in programming. Whether you're processing data, parsing text, or iterating through a collection of items, you need a reliable and efficient way to perform these repetitive actions. This is where the for loop in Python comes in as a versatile and indispensable tool.

In this post, we will learn in detail about the 'for' loops in Python. We'll explore their syntax, applications, examples, how to use, and best practices. By the end of this article, you'll have a solid grasp of how 'for' loops work and how to leverage their potential to simplify your code and save you time.

What is for Loop in Python?

A 'for' loop in Python is a control flow structure used for iterating over a sequence of items, such as elements in a list, characters in a string, or key-value pairs in a dictionary. It allows you to repeatedly execute a block of code for each item in the sequence. 

The 'for' loop is a fundamental programming construct that simplifies repetitive tasks and makes it easy to work with collections of data.

So, if there is a sequence object, say a list, then we can use the for loop to iterate over items in the list. 

The functionality of the for loop in Python is almost similar to what it is in other programming languages.

For loop Syntax in Python

The basic syntax of 'for' loop in Python is as follows:

for variable in iterable:
    # Code to be executed for each item in the iterable

Here's a breakdown of the components:

  • for: This is the keyword that initiates the 'for' loop.

  • variable: This is a user-defined variable that represents the current item in the iterable during each iteration. You can choose any valid variable name.

  • in: This is another keyword used to specify that you are iterating "in" the items of the iterable.

  • iterable: The iterable is the collection of items over which you want to iterate. It can be a list, string, tuple, dictionary, or any other sequence-like object.

Iterable in for Loop in Python

The iterable plays a crucial role in the 'for' loop as it defines the set of items you want to loop through. The 'for' loop will execute the indented code block for each item in the iterable, one item at a time, until all items have been processed.

The iterable can be of various types:

  • Lists and Sequences: 

Lists, tuples, and other sequence-like data structures are commonly used as iterables. You can loop through each element in the list or sequence and perform operations on them within the loop.

  • Strings: 

Strings in Python are also iterable. When you use a 'for' loop with a string, it iterates character by character through the string, allowing you to manipulate or analyze individual characters.

  • Dictionaries: 

When using a 'for' loop with dictionaries in Python, you can iterate through the keys, values, or key-value pairs (items) within the dictionary. This is helpful for tasks like data extraction and manipulation.

  • Range: 

The range() function generates a sequence of numbers, and it is often used as an iterable for numerical iterations. You can loop through numbers within a specified range.

How Does for Loop Work in Python?

A 'for' loop, also called for statement in Python, works the following way::

  • Initialization

The 'for' loop begins with an initialization step. It defines a variable that will represent each item in the sequence during each iteration. This variable can have any name you choose.

  • Iteration

The 'for' loop iterates over the items in the sequence, one at a time, starting from the first item and progressing to the last. For each iteration, the variable defined in the initialization step takes on the value of the current item in the sequence.

  • Execution of Code Block

Within the 'for' loop, there is an indented block of code that will be executed during each iteration. This is where you perform actions or operations on the current item.

  • Update Variable (Optional)

After each iteration, you can optionally update the variable. For example, you might increment a counter variable, change the current index in the case of lists, or use it for other purposes.

  • Iteration Continues

The loop continues to iterate through the items in the sequence until it reaches the end of the sequence. At each iteration, the loop checks whether there are more items in the sequence. If there are no more items, the loop exits.

  • Completion

Once all items have been processed, the 'for' loop completes, and the program continues with any subsequent code after the loop.

Here's a simple example to understand how a Python 'for' loop works:

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

In this example:

  • The 'for' loop iterates over the fruits list.

  • During each iteration, the variable fruit takes on the value of the current fruit in the list.

  • The code block prints "I like" followed by the name of the current fruit.

  • After all fruits have been processed, the loop completes, and the program continues.

Examples of ‘for’ loops in Python

Here are some Python for loop examples:

1. Iterating Over a List:

Suppose you have a list of fruits, and you want to print each fruit's name using a 'for' statement in Python:

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

In this example, the 'for' loop iterates over the fruits list, and the fruit variable takes on the value of each element in the list during each iteration. The loop prints each fruit's name.

Output:

apple
banana
cherry
date

2. Iterating Over a String:

Now, let's consider a simple 'for' loop in Python that iterates through a string and prints each character:

text = "Hello, World!"
for char in text:
    print(char)

In this case, the 'for' loop iterates over the string text, and the char variable represents each character in the string during each iteration.

Output:

H
e
l
l
o
,

W
o
r
l
d
!

3. Summing Numbers in a List:

You can use a 'for' loop in Python to calculate the sum of numbers in a list:

numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print("The sum of numbers is:", total)

Output:

The sum of numbers is: 15

4. Printing a Range of Numbers:

You can use the range() function with a 'for' loop in Python to print a sequence of numbers:

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

Output:

1
2
3
4
5

5. Iterating Through a Dictionary:

When iterating through a dictionary, you can access keys, values, or key-value pairs (items):

student_grades = {"Alice": 92, "Bob": 85, "Charlie": 78}
for student, grade in student_grades.items():
    print(student, "scored", grade, "marks.")

Output:

Alice scored 92 marks.
Bob scored 85 marks.
Charlie scored 78 marks.

How to Use for loop in Python?

To use a 'for' loop in Python, follow these steps:

1. Define Your Iterable: Start by having a collection of items over which you want to iterate. This could be a list, string, tuple, dictionary, or any other iterable data structure.

2. Write the 'for' Loop: Use the 'for' loop syntax to define the loop. Here's the basic structure:

for variable in iterable:
    # Code to be executed for each item in the iterable
  • variable: Choose a variable name that represents the current item during each iteration.

  • iterable: The iterable you defined in step 1.

3. Write Code Inside the Loop: Inside the 'for' loop, write the code that you want to execute for each item in the iterable. The code will be indented to indicate that it's part of the loop.

4. Optional: Update the Variable: After each iteration, you can update the variable if needed. For example, if you're iterating over a list and want to keep track of the index, you can manually increment the index variable.

5. Repeat Until the End of the Iterable: The 'for' loop will iterate over each item in the iterable, executing the code for each item, and it will continue until it reaches the end of the iterable.

range() Function for Numerical Iterations in for loop

The range() function in Python is a versatile tool that's used with 'for' loops to facilitate numerical iterations. It generates a sequence of numbers that can be used to control the number of iterations or access specific indices in a sequence. 

  • Creating a Range Object:

The range() function generates a range object that represents a sequence of numbers. You can specify the starting point, ending point, and step size as arguments.

range_obj = range(start, stop, step)

start: The starting value of the range (inclusive). It's optional and defaults to 0 if not provided.

stop: The ending value of the range (exclusive). This value is required.

step: The step size, indicating how the range increments from one value to the next. It's optional and defaults to 1 if not provided.

  • Using 'for' Loops with range():

You can use a 'for' loop to iterate through the sequence of numbers generated by the range() function.

for i in range(5):  # This will generate numbers from 0 to 4.
    # Code to be executed in each iteration

The loop runs for each value produced by the range() object, allowing you to perform actions for each number in the specified range.

  • Iterating Through a Sequence:

The range() function is particularly useful when you want to perform numerical iterations, such as iterating through a list, string, or any other sequence data structure.

my_list = [10, 20, 30, 40, 50]
for i in range(len(my_list)):
    item = my_list[i]
    # Code to work with each item in the list

In this example, the 'for' loop iterates through indices generated by the range() function, and you can access each item in the list using these indices.

  • Skipping Iterations:

The range() function's step argument allows you to specify the step size, which determines the interval between numbers. You can use this to skip iterations.

for i in range(0, 10, 2):  # This will generate numbers 0, 2, 4, 6, and 8.
    # Code to be executed in each iteration

In this example, the loop iterates through numbers in increments of 2.

  • Flexible Control:

The range() function provides flexible control over numerical iterations. It's commonly used for a wide range of tasks, from simple counting to more complex data processing and algorithms.

Use of Loop Control Statements in Python

Loop control statements like 'break' and 'continue' are used within 'for' loops in Python to modify the normal flow of the loop and control the execution of the code. They provide you with the ability to add conditional logic to your loops and can be very useful for more complex scenarios. 

'break' Statement:

  • The 'break' statement in Python is used to exit a loop prematurely when a certain condition is met.

  • When 'break' is encountered, the loop terminates immediately, and the program execution continues with the code after the loop.

  • 'break' is used when you want to exit a loop early, perhaps when you've found the result you were looking for or encountered an error condition.

Example using 'break' in a 'for' loop:

numbers = [1, 2, 3, 4, 5]
target = 3
for num in numbers:
    if num == target:
        print("Found the target!")
        break

In this example, the 'break' statement is used to stop the loop as soon as the target value is found. 

'continue' Statement:

  • The 'continue' statement in Python is used to skip the current iteration of the loop and move on to the next iteration.

  • When 'continue' is encountered, the remaining code within the current iteration is skipped, and the loop continues with the next item in the iterable.

  • 'continue' is used when you want to avoid executing the rest of the loop's code for a particular item in the sequence.

Example using 'continue' in a 'for' loop:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        continue  # Skip even numbers
    print(num)

In this example, the 'continue' statement is used to skip even numbers and only print odd numbers.

Nested for Loops in Python

Nested 'for' loops means the use of one 'for' loop inside another 'for' loop. This concept allows you to create more complex iterations and solve a wide range of problems. 

In a nested loop, the inner loop is completely executed for each iteration of the outer loop. This means that for each value of the outer loop's variable, the inner loop will iterate through its entire sequence. 

Nested loops are a fundamental concept in computer programming and are especially useful for tasks that involve multidimensional data structures, such as 2D lists and matrices.

Uses of Nested Loops:

Nested loops can be used for various purposes, including but not limited to:

  • Iterating over 2D Arrays or Matrices: When you have a 2D list or a matrix, you can use nested loops to access each element individually. The outer loop typically iterates through rows, and the inner loop iterates through columns.

  • Creating Patterns: Nested loops are often used to create patterns, such as patterns of stars or numbers, by controlling the number of rows and columns.

  • Searching for Elements: You can use nested loops to search for specific elements or combinations of elements within a data structure.

  • Computing Grids: When dealing with grids, nested loops can be used to calculate values or perform operations on each cell within the grid.

Examples of Nested 'for' Loops:

1. Iterating Over a 2D List:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element, end=' ')
    print()

In this example, the outer loop iterates through each row of the matrix, and the inner loop iterates through each element in the current row. This allows you to access and process each element individually.

2. Creating a Pattern:

rows = 5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print('*', end=' ')
    print()

This nested loop example creates a pattern of stars. The outer loop controls the number of rows, and the inner loop controls the number of stars printed on each row.

3. Searching for Elements:

data = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
target = 50
for row_index, row in enumerate(data):
    for col_index, element in enumerate(row):
        if element == target:
            print(f"Found {target} at position ({row_index}, {col_index}).")

List Comprehensions Using for loop in Python

List comprehensions are a concise and Pythonic way to create lists using 'for' loops. They allow you to generate new lists by applying an expression to each item in an iterable, all in a single line of code. List comprehensions are known for their readability and efficiency, and they are a powerful tool for creating lists without the need for explicit 'for' loops.

Syntax of List Comprehensions:

The basic syntax of a list comprehension is as follows:

new_list = [expression for item in iterable]
  • new_list: The list to be created.

  • expression: The operation or transformation to be applied to each item.

  • item: Represents each item in the iterable.

  • iterable: The source of items over which you want to iterate.

Examples of List Comprehensions:

Here are examples of list comprehensions compared to traditional 'for' loops:

1. Using a 'for' Loop to Create a List:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)

2. Using a List Comprehension:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]

The list comprehension accomplishes the same task in a more concise and readable way. It generates the squared_numbers list by squaring each number from the numbers list.

3. Using a 'for' Loop with a Condition:

numbers = [1, 2, 3, 4, 5]
even_numbers = []
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

4. Using a List Comprehension with a Condition:

numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]

In this case, the list comprehension filters out only the even numbers from the numbers list.

Uses of for Loops in Python

'for' loops in Python are versatile and essential constructs used in a wide range of practical scenarios:

1. Iterating Over Collections:

'for' loops are frequently used to iterate over elements in data collections such as lists, tuples, sets, and dictionaries. This is essential for processing and analyzing data.

2. List Comprehensions:

List comprehensions use 'for' loops to create new lists by applying an expression to each item in an existing iterable. They are a concise and efficient way to generate lists.

3. Iterating Over Strings:

You can use 'for' loops to iterate over characters in a string, making it possible to manipulate or analyze textual data.

4. Enumerating Items:

The enumerate() function with a 'for' loop is useful for iterating through both the items and their indices in a collection.

5. File Handling:

'for' loops are used to read and process lines in text files. You can iterate through the lines of a file to extract, transform, or analyze data.

6. Nested Loops:

'for' loops can be nested to handle multidimensional data structures or to perform operations on a grid-like structure. This is common in computer graphics, matrix calculations, and puzzles.

7. Data Processing and Filtering:

'for' loops are instrumental in filtering, transforming, or aggregating data elements based on specific criteria. For instance, you can calculate statistics or filter items meeting certain conditions.

8. Generating Sequences:

You can use 'for' loops to generate sequences of numbers or other patterns. This is useful for tasks like printing a range of dates or creating a calendar.

9. Iterating Through Dictionaries:

'for' loops can be used to iterate through dictionary keys, values, or key-value pairs, allowing you to process and manipulate dictionary data.

10. Web Scraping and API Calls:

'for' loops are employed when making multiple requests to web APIs or scraping data from web pages. Each iteration can correspond to a request to retrieve data.

11. Automation:

In automation tasks, 'for' loops can help you perform repetitive actions, such as sending emails to a list of recipients, processing files in a directory, or executing a series of commands.

12. Algorithms and Data Structures:

'for' loops play a crucial role in implementing various algorithms and data structures, like searching, sorting, and traversing trees and graphs.

13. Simulation and Modeling:

In simulations and modeling, 'for' loops are used to simulate the behavior of systems or to model iterative processes.

Best Practices to Write Efficient and Readable 'for' loops in Python

Writing efficient and readable 'for' loops is crucial for maintaining code quality and performance. 

Here are some best practices to follow:

  • Use Descriptive Variable Names: 

Choose meaningful variable names that describe the purpose of the loop. This makes your code more readable and self-explanatory.

# Good
for student in student_list:
    ...
# Avoid
for s in lst:
    ...
  • Keep the Loop Simple: 

Avoid nesting too many loops or adding complex logic within a single loop. If a loop becomes too complex, consider breaking it into smaller, more manageable functions or using helper functions.

  • Use List Comprehensions When Appropriate: 

For simple transformations and filtering of data, consider using list comprehensions. They can make your code more concise and readable.

squares = [x ** 2 for x in numbers]
  • Minimize Loop Body Length: 

Keep the code inside the loop body concise and focused on a single task. If the loop body becomes too long, consider breaking it into functions for better readability.

  • Precompute Values: 

If you need to compute values that don't change within the loop, calculate them before the loop starts to avoid redundant calculations.

total = 0
for number in numbers:
    total += number
  • Avoid Modifying the Iterable in Place: 

Modifying a list, dictionary, or other iterable while iterating over it can lead to unexpected behavior. If you need to modify the iterable, consider creating a new one with the desired changes.

  • Use 'enumerate' for Indices: 

When you need both the item and its index while iterating, use the enumerate() function to make your code more readable.

for index, item in enumerate(items):
    ...
  • Comment Your Code: 

Add comments when the purpose of the loop or the logic inside it is not immediately clear. Comments can help other developers understand your code more easily.

  • Avoid Infinite Loops: 

Ensure that your loops have a clear exit condition to prevent infinite loops, which can lead to program crashes or excessive resource consumption.

  • Profile and Optimize: 

If you find that a 'for' loop is a performance bottleneck in your code, consider profiling your code to identify areas for optimization. You can use tools like cProfile to analyze your code's performance.

  • Consider Built-in Functions: 

Python provides several built-in functions (e.g., sum(), max(), min(), all(), any()) that can often replace custom 'for' loops for common tasks.

  • Use a Generator When Possible: 

If you're just iterating through a sequence without the need to store intermediate results, consider using a generator to conserve memory.

for number in (x for x in numbers if x % 2 == 0):

QUIZ!

What will be the outcome of the Python code below?

x = ['a', 'c']

for i in x:

    i.upper()

print(x)

Select the correct answer

Did you find this article helpful?