We have the answers to your questions! - Don't miss our next open house about the data universe!

Python loops: A Guide for Efficient Iteration

- Reading Time: 4 minutes
Python loops

Automation and repetition are ubiquitous concepts in programming. Imagine having to perform the same action hundreds or even thousands of times. This would not only be tedious, but also a source of errors. Programming languages such as Python offer powerful tools for managing these repetitions: loops.

Whether you’re browsing a list of data, repeating an operation until a condition is met, or even generating sequences, loops are of paramount importance.

 

💡Related articles:

Matplotlib: Master Data Visualization in Python
Python Crash Course: Get started
Mastering Machine Learning in Python: Data-Driven Success
Python Programming for Beginners – Episode 3
Django: All about the Python web development framework
NumPy : the most used Python library in Data Science

The "for" loop

The for loop is one of the most frequently used control structures in Python. It allows you to step through elements of a sequence (such as a list, tuple – an immutable collection of elements – string) or other iterable objects, and execute a block of code for each element.

1. Basic concept

Its syntax is simple and intuitive:

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

For example, to display each letter of a string :

				
					for letter in "Python":
    print(letter)
				
			

2. Use with the range() function

One of the most commonly used functions with the for loop is range (). It generates a sequence of numbers, which is useful for executing a loop a defined number of times.
				
					for i in range(5):
    print(i)
				
			
The example above displays numbers from 0 to 4 (range(5) generates a sequence that starts at 0 and stops before 5).

3. Browse lists

Lists are among the objects most commonly used with the forloop. To display the names in a list, for example:
				
					noms = ["Alice", "Bob", "Charlie"]
for nom in noms:
    print(nom)
				
			

4. Nested loops

It’s possible to use a for loop inside another for loop. For example, to display a multiplication table:
				
					for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")
				
			

Nested loops can be powerful, but should be used with caution to avoid excessive complexity.

The "while" loop

In contrast to the for loop, which traverses a sequence of elements, the while loop executes a block of code as long as a given condition is true. It offers additional flexibility, but also requires careful attention to avoid infinite loops.

1. Basic concept

Its syntax is as follows:

				
					while condition:
    # block of code to be executed as long as the condition is true
				
			

For example, to display numbers from 0 to 4 :

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

Note the importance of incrementing variable i at each iteration to avoid an endless loop.

2. Precautions

The main danger with the while loop is the risk of creating an infinite loop, where the block of code executes indefinitely because the condition always remains true. To avoid this:
  • Make sure you have a condition that will become false at some point.
  • Check conditions and control variables regularly during the development phase.

Let’s take an example of an infinite loop. Suppose we want to double the value of a variable until it reaches (or exceeds) a certain threshold.

				
					limit = 100
value = 1

while value < limit:
    print(value)
    # Forgot to increment or modify value
   # Instead of doubling the value as planned, we forgot this step
    # value *= 2
				
			
In the above example, the condition value < limit will always be true since the value is never modified.

3. Practical use

The while loop is particularly useful when the number of iterations is not known in advance. For example, to ask the user to enter a correct password:
				
					password = "secret
input = ""
while input != password:
    input = input("Enter password: ")
print("Access granted.")
				
			
The while loop is a valuable tool. Although it offers great flexibility, it is crucial to use it with care and discernment.

Flow control in loops

Python offers several tools for managing the flow of execution within loops, allowing greater flexibility.

1. Break and continue instructions

  • break : Exit the current loop immediately. Execution resumes at the code block following the loop.

Example: Find the first number divisible by 7 in a list.

				
					numbers = [3, 5, 8, 12, 14, 18]
for n in numbers:
    if n % 7 == 0:
        print(f "The first number divisible by 7 is {n}.")
        break
				
			
  • continue : Interrupts the current iteration and proceeds to the next, without exiting the loop.

Example: Display all numbers except those divisible by 3.

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

2. The else clause with loops

Little known, the else clause can be used with the for and while loops. It is executed when the loop ends normally (i.e. without being interrupted by a break). Example : Check if a number is prime.
				
					n = 17
for i in range(2, n):
    if n % i == 0:
        print(f"{n} is not a prime number.")
        break
else:
    print(f"{n} is a prime number.")
				
			
In this example, if no divisor is found for n, the else clause will be executed.

Tips and best practices

Infinite loops

Infinite loops, especially with while, are a frequent pitfall. Make sure you have a clear stop condition.

List comprehension

A Python feature to create lists in a concise and elegant way. Instead of a loopfor, use list comprehension..

Example : Create a list of the squares of the numbers from 0 to 9.

squares = [x**2 for x in range(10)]

 

Limit the depth of interlocking loops

Avoid too many overlapping loops, as they complicate legibility. For more than three levels, consider other solutions.

Document

A comment clarifies the purpose of the loop, especially for complex loops.

Beware of complexity

Structure your loops wisely to optimize performance. Avoid costly in-loop operations.

Conclusion

Mastering loops is crucial for any Python developer. They offer the power to automate repetitive tasks, making code more efficient and concise. By following best practices and understanding the subtleties, you’ll optimize your programs while avoiding common pitfalls.

You are not available?

Leave us your e-mail, so that we can send you your new articles when they are published!
icon newsletter

DataNews

Get monthly insider insights from experts directly in your mailbox