Tutorial

For Loops in Python

5 min read

In this article, we will learn about the different types of for loops in Python and how to use them effectively in our code. The loop is a fundamental concept in Python programming. And implementation of for loop is particularly powerful and versatile.

We will start with the basic standard “for” loop which includes how to iterate over a sequence and use the range function. Next, we will see how the “for-each” loop differs from the standard for loop.

Types of For loop in Python

There are two main types of for loops in Python:

  1. The standard for loop iterates over a sequence of items (such as a list or string) and assigns each item to a variable on each iteration.
  2. And “for-each” loop, is implemented using the for keyword along with the in the keyword. This type of loop iterates over the elements of an iterable object (such as a list or dictionary), rather than using an index.

How can I write for loop in Python?

Below is the syntax for loop in Python with code examples and explanations.

Syntax of For loop in Python

The syntax for a standard for loop in Python is as follows:

for variable in sequence:
    # code to execute on each iteration

Here, the for in Python keyword is used to initiate the loop. The variable is a placeholder that takes on the value of the next item in the sequence on each iteration. The sequence is the list, tuple, string, etc. that we want to iterate over. The code indented under the for statement is executed on each iteration.

Example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

The output for this code will be:

1
2
3
4
5

Here, the for loop helps us to print out the contents of the numbers list through each iteration.

It is important to note that the for loop must be indented properly, otherwise, we will get an IndentationError.

Python For Loop using Python range()

One common use of for loops in Python is to iterate over a range of numbers using the range() function. The range() function generates a sequence of numbers within a specified range.

The basic syntax for using the range() function is as follows:

range(start, stop, step)

Here, the start is the first number in the range (default is 0). The stop is the last number in the range (this number is not included in the range). The step is the difference between each number in the range (default is 1).

Example of Python for and range function-

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

The output for this code will be:

2
4
6
8

Here, we see that using the range() function in a for loop in Python we are able to print out the numbers between 2 and 10(excluded) with a difference of 2 digits.

It’s important to note that when using range() in a for loop, the loop variable (i.e., i in the above example) will take on the value of the next number in the range on each iteration, rather than the next item in a list or other iterable object.

The range() function is very useful for performing a specific number of iterations or for generating a sequence of numbers for use in mathematical operations or other calculations. Moreover, the range() function can also be converted to a list, tuple, or set with the use of list(), tuple(), or set().

For loop in Python with index

Sometimes it is useful to know the index of the current item in a loop.

Python provides the built-in function enumerate() which can be used in combination with the for loop to get the index of the current item.

The syntax of For loop is as follows-

for index, variable in enumerate(sequence):
    # code to execute for each iteration

Example of For loop in Python with index-

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

The output of this will be:

0 apple
1 banana
2 cherry

Here, it prints each element and its corresponding index in the list fruits on a new line.

The enumerate() function returns a tuple, where the first element is the index and the second element is the value of the current item in the loop.

Note: When we are looping through a collection, it is a good practice to use the enumerate() function instead of using the range() function with the length of the collection and the index to access the elements directly. This is because it makes your code more readable.

For Loop with Else statement

In Python, the for loop can be used in conjunction with an else block. The else block is executed after the loop completes, but only if the loop completes normally (i.e., without being interrupted by a break statement).

The syntax for a for loop with an else block is as follows:

for variable in sequence:
    # code to execute on each iteration
else:
    # code to execute after the loop completes

Example using the above syntax:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)
else:
    print("Loop complete.")

The output for this code will be:
1
2
3
4
5
Loop complete.

Here, we are using a for loop with an else block to iterate over a list of numbers and print each one. If the loop completes normally, the else block will print “Loop complete“.

This is useful for situations where we want to perform certain actions after the loop completes, but only if the loop completes normally. For example, we might use an else block to check for errors or missing data after processing a large dataset, or to display a message to the user after a successful operation.

Note: If the loop is interrupted by a break statement, the else block will not be executed. So it’s important to keep that in mind when using else block with for loop.

Conclusion

For loops in Python is an essential tool for Python programmers. Whether you are a beginner or an experienced developer, understanding how to use for loops effectively is crucial for writing efficient and effective code.

In this article, we’ve covered the basics of the standard for loop, including how to iterate over sequences and use the range() function. We’ve also learned about the “for-each” loop and how it differs from the standard for loop. Then we saw how to use else statements in for loops.

There are other types of loops in Python as well

Hope you like the tutorial, learn Python with the help of a Python tutor