Sharing is caring 🙂

Python provides several ways to perform repetitive tasks, known as loops. Loops are used to execute a block of code repeatedly as long as a certain condition is met. This allows for efficient and organized code that can handle repetitive tasks with ease. In this tutorial, we will be discussing the two main types of loops in Python: the “for” loop and the “while” loop. We will also cover the various methods and techniques for using these loops effectively in your code.

The “for” Loop Syntax

The “for” loop in Python is used to iterate over a sequence of items, such as a list, tuple, or string. The basic syntax for a “for” loop is as follows:

for variable in sequence:
    # code to be executed

The “variable” in the syntax above represents the current item in the sequence, and the “sequence” is the group of items that the loop will iterate over. The code within the loop will be executed once for each item in the sequence.

For example, if we have a list of numbers and we want to print each number in the list, we can use a “for” loop like this:

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

This will output:

1
2
3
4
5

It’s also possible to use the enumerate() function with a for loop to get the index and the element of the list.

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

This will output:

0 1
1 2
2 3
3 4
4 5

It’s also possible to loop over other types of sequences such as strings and tuples, in the same way.

Using the “range()” Function with “for” Loops

The “range()” function in Python is a built-in function that is commonly used in conjunction with “for” loops. It allows for the creation of a range of numbers, which can then be iterated over in a loop. The basic syntax for the “range()” function is as follows:

range(start, stop, step)
  • “start” is the first number in the range (default is 0 if not specified)
  • “stop” is the last number in the range (this number is not included in the range)
  • “step” is the increment/decrement value (default is 1 if not specified)

For example, the following code will print the numbers 0 to 9:

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

This will output:

0
1
2
3
4
5
6
7
8
9

If you want to create a range of numbers with a specific start and stop value and increment/decrement value, you can use the following syntax:

for i in range(start, stop, step):
    # code to be executed

For example, the following code will print the even numbers from 2 to 8:

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

This will output:

2
4
6
8

It’s also possible to use negative values for step, to loop in reverse order.

for i in range(9, 2, -2):
    print(i)

This will output:

9
7
5
3

It’s also important to note that you can use the range() function with enumerate() function to get the index and the element of the list, for example:

for i, num in enumerate(range(10)):
    print(i, num)

This will output:

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Looping through Lists and Other Iterable Objects

In Python, a list is a collection of items that can be iterated over in a loop. The “for” loop can be used to iterate over the items in a list and perform a certain action for each item. For example, the following code will print each item in a list of fruits:

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

This will output:

apple
banana
cherry

In addition to lists, there are other types of iterable objects in Python, such as tuples, sets, and dictionaries. These types of objects can also be iterated over using a “for” loop.

For example, you can loop through the items of a tuple:

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

This will output:

1
2
3
4
5

You can also loop through the items of a set:

my_set = {1, 2, 3, 4, 5}
for num in my_set:
    print(num)

This will output (the order of the output may be different):

1
2
3
4
5

For dictionaries, you can use the .items() method to loop over the key, value pairs, for example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)

This will output:

a 1
b 2
c 3

You can also use the .keys() or .values() method to loop through the keys or values, respectively.

It’s also possible to use the zip() function to iterate over multiple lists in a for loop, for example:

x = [1, 2, 3]
y = [4, 5, 6]
for a, b in zip(x, y):
    print(a, b)

This will output:

1 4
2 5
3 6

In general, any object that can be iterated over, such as a file object or a custom class that implements the __iter__() method can be used with a “for” loop.

Nested Loops and Iterating Over Multiple Lists

In Python, it’s possible to nest one loop inside of another loop, creating a nested loop. This allows for more complex iteration and is often used to iterate over multiple lists at the same time.

For example, let’s say we have two lists of numbers, and we want to print all the possible pairs of numbers from these lists. We can use nested loops to achieve this:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
for num1 in list1:
    for num2 in list2:
        print(num1, num2)

This will output:

1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6

It’s also possible to use the zip() function to iterate over multiple lists in a single for loop:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
for num1, num2 in zip(list1, list2):
    print(num1, num2)

This will output the same as the previous example:

1 4
2 5
3 6

It’s also possible to use the itertools.product() function to get the Cartesian product of multiple lists, for example:

import itertools
list1 = [1, 2]
list2 = ['a', 'b']
list3 = ['x', 'y']
for num1, num2, num3 in itertools.product(list1, list2, list3):
    print(num1, num2, num3)

This will output:

1 a x
1 a y
1 b x
1 b y
2 a x
2 a y
2 b x
2 b y

It’s important to note that nested loops can be computationally expensive and can cause performance issues if the number of iterations is large. Hence, it’s important to use them judiciously in your code.

Using the “enumerate()” Function in “for” Loops

The “enumerate()” function in Python is a built-in function that is commonly used in conjunction with “for” loops. It allows for the iteration over a sequence of items, such as a list, tuple, or string, and also returns the index of the current item along with the item itself. This is useful when you need to keep track of the index of the current item while iterating through the sequence.

The basic syntax for the “enumerate()” function is as follows:

enumerate(sequence, start=0)
  • “sequence” is the group of items that the loop will iterate over.
  • “start” is the index of the first item (default is 0 if not specified)

For example, the following code will print the index and the item of a list of fruits:

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

This will output:

0 apple
1 banana
2 cherry

As you can see, the enumerate() function returns a tuple of the index and the current item, so you can unpack them into two different variables, like i and fruit in the example above.

It’s also possible to use the enumerate() function in other types of sequences such as strings and tuples, and with other types of iterable objects like dictionaries and sets.

For example, you can use the enumerate() function to loop through the items of a tuple and print the index and the item:

numbers = (1, 2, 3, 4, 5)
for i, num in enumerate(numbers):
    print(i, num)

This will output:

0 1
1 2
2 3
3 4
4 5

You can also use the enumerate() function to loop through the key-value pairs of a dictionary and print the index and the pair:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for i, (key, value) in enumerate(my_dict.items()):
    print(i, key, value)

This will output:

0 a 1
1 b 2
2 c 3

Using the enumerate() function can make your code more readable, and can also save you from having to create a separate counter variable to keep track of the index while iterating through a sequence.

Looping in Reverse

It’s possible to loop through a sequence of items in reverse order using a “for” loop. There are a few different ways to accomplish this, depending on the type of sequence you are working with.

One way to loop through a sequence in reverse order is to use the built-in reversed() function. This function returns an iterator that produces the items of a sequence in reverse order.

For example, the following code will print the items of a list of numbers in reverse order:

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

This will output:

5
4
3
2
1

It’s also possible to loop through a range of numbers in reverse order by using the range() function with a negative step value.

for i in range(5, 0, -1):
    print(i)

This will output:

5
4
3
2
1

Another way to loop through a list in reverse order is to use negative indexing. Since lists in Python are ordered collections of items, each item has an index, starting from 0. Negative indexing allows you to access items from the end of the list, counting backwards.

numbers = [1, 2, 3, 4, 5]
for i in range(-1, -len(numbers)-1, -1):
    print(numbers[i])

This will output the same as the first example:

5
4
3
2
1

When using the reversed() function on a list, it returns an iterator, so it doesn’t change the original list, so it’s more memory efficient. If you want to reverse the list in-place, you can use the .reverse() method.

Also, when using negative indexing, the original list is not modified, but it’s less memory efficient than using the reversed() function.

The “while” Loop in Python

The “while” loop in Python is used to repeatedly execute a block of code as long as a certain condition is met. The basic syntax for a “while” loop is as follows:

while condition:
    # code to be executed

The “condition” in the syntax above is a boolean expression that is evaluated before each iteration of the loop. If the condition is True, the code within the loop is executed, and then the condition is evaluated again. If the condition is False, the loop is terminated and the program continues with the next line of code after the loop.

For example, the following code will print the numbers from 1 to 5:

i = 1
while i <= 5:
    print(i)
    i += 1

This will output:

1
2
3
4
5

It’s important to note that if the condition is always True, the loop will run indefinitely, resulting in an infinite loop. It’s important to have a way to break out of the loop in this case, usually by changing the value of the condition inside the loop.

For example, the following code will ask the user for input until they type “stop”:

while True:
    user_input = input("Type something: ")
    if user_input == "stop":
        break
    else:
        print("You typed: ", user_input)

Also, you can use the else clause with the while loop, which will execute after the loop has finished, but only if the loop has finished normally (i.e. the loop has not been interrupted by a break statement)

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print("The loop has finished")

This will output:

1
2
3
4
5
The loop has finished

It’s important to use the “while” loop with caution, as it can easily lead to infinite loops if the condition is not properly set and the loop not properly controlled.

Breaking and Continuing in Loops

In Python, it’s possible to break out of a loop or skip an iteration using the “break” and “continue” statements, respectively.

The “break” statement is used to exit a loop early, before it has finished iterating through all the items. When the “break” statement is encountered, the loop is immediately terminated, and the program continues with the next line of code after the loop. For example, the following code will print the numbers from 1 to 10, but will exit the loop when the number 5 is reached:

for i in range(1, 11):
    if i == 5:
        break
    print(i)

This will output:

1
2
3
4

The “continue” statement is used to skip an iteration of a loop. When the “continue” statement is encountered, the current iteration of the loop is skipped, and the program continues with the next iteration. For example, the following code will print the even numbers from 1 to 10:

for i in range(1, 11):
    if i % 2 != 0:
        continue
    print(i)

This will output:

2
4
6
8
10

It’s important to use these statements judiciously, as they can make the code harder to understand and maintain. It’s also possible to use the break and continue statements with the while loop as well. The same logic applies when using “break” and “continue” statements with the “while” loop.

For example, the following code will print the numbers from 1 to 10, but will exit the loop when the number 5 is reached:

i = 1
while i <= 10:
    if i == 5:
        break
    print(i)
    i += 1

This will output:

1
2
3
4

And the following code will print the even numbers from 1 to 10:

i = 1
while i <= 10:
    if i % 2 != 0:
        i += 1
        continue
    print(i)
    i += 1

This will output:

2
4
6
8
10

In both examples, the break statement allows to exit the loop early and the continue statement skips an iteration of the loop.

Using the “else” Clause in Loops

The “else” clause in loops is executed after the loop has finished, but only if the loop has finished normally (i.e. the loop has not been interrupted by a “break” statement).

The “else” clause can be used with both “for” and “while” loops.

For example, the following code will print the numbers from 1 to 5, and will print “The loop has finished” after the loop has completed:

for i in range(1, 6):
    print(i)
else:
    print("The loop has finished")

This will output:

1
2
3
4
5
The loop has finished

And the following code will print the even numbers from 1 to 10 and will print “The loop has finished” after the loop has completed:

i = 1
while i <= 10:
    if i % 2 != 0:
        i += 1
        continue
    print(i)
    i += 1
else:
    print("The loop has finished")

This will output:

2
4
6
8
10
The loop has finished

If the loop is interrupted by a “break” statement, the “else” clause will not be executed.

The “else” clause in loops can be useful for performing some action or providing feedback to the user when the loop has been completed normally.

In general, the else clause in loops is not a common feature in many programming languages but it can be useful in some specific scenarios where you want to do some action after the loop has completed normally.

Sharing is caring 🙂