How To Replace Nested For Loops In Python?

We all adore nested loops. But are we? After five layers of indentation, you need more clarification on that. You wish there were another option as your code starts to look bad. Thankfully, there is! Product (), one of itertools’ functions, can take the place of one of your loops.

In this article, find out how to replace nested for loops in Python and find out what there is to know about nested loops. So let’s dive right in!

Advertising links are marked with *. We receive a small commission on sales, nothing changes for you.

How To: Replacing Nested For Loops In Python With Examples

How To Replace Nested For Loops In Python?

As mentioned in the introduction of this article, itertools is used to replace nested for loops in Python. What exactly is itertools.product? 

It is a function that accepts a set of iterables and returns the Cartesian product of those iterables. To put it another way, all ordered tuples with items derived from each iterable. 

The following tuples would be produced if [1, 2] and [‘a’, ‘b’, ‘c’] were combined: (1, ‘a’), (1, ‘b’), (1, ‘c’), (2, ‘a’), (2, ‘b’), and (2, ‘c’.

Since the values are only calculated when accessed, itertools.product is optimized for performance and memory utilization. 

As a result, your software will not only appear nicer, but it may also run quicker and use less memory.

Let’s look at some instances now.

In the first example, Przemek called a method to get prefixes for all possible concatenations of regions and roles.

Although its advantages are not immediately apparent in this situation, he believes it clarifies the purpose. For example, we may get values from iterables in a single step and combine dependent variables. Another argument could be added in the future.

pfx_list = [] for region in regions: for role in pfx_roles: pfx_list.extend(get_pfxs(region=region, role=role))
pfx_list = [] for region, role in itertools.product(regions, pfx_roles): pfx_list.extend(get_pfxs(region=region, role=role))

Another illustration relates to creating network device names made up of multiple parts.

It is instantly clear that itertools.product version appears superior, making it more straightforward to understand what is happening, even if we are decreasing four levels of nesting to one.

Additionally, Przemek did not iterate over range(1, 3), and once he chose to add an id to device names, it was much simpler to add it to the itertools.product version.

iata_cc = ['bai', 'mex', 'tyo', ] dev_types = ['switch', 'router'] dev_roles = ['core', 'edge']
for cc in iata_cc: for dev_t in dev_types: for dev_r in dev_roles: for dev_id in range(1, 3): print('{cc}-{dev_t}-{dev_r}-{dev_id}'. format(cc=cc, dev_t=dev_t, dev_r=dev_r, dev_id=dev_id))
for cc, dev_t, dev_r, dev_id in itertools.product(iata_cc, dev_types, dev_roles, range(1, 3)): print('{cc}-{dev_t}-{dev_r}-{dev_id}'. format(cc=cc, dev_t=dev_t, dev_r=dev_r, dev_id=dev_id))

Python Nested Loops: What Is There To Know About Nested Loops?

The for loop and the while loop are the two loops available in the Python programming language. 

These loops allow us to build nested loops in Python. They are loops that are nested within other loops. For instance, while loops within while loops, for loops within for loops, etc.

Here is an example of Basic Nested Loops in Python:

x = [1, 2]
y = [4, 5]

for i in x:
for j in y:
	print(i, j)

And this is what it would look like: 

1 4 1 5 2 4 2 5 

Break Statement In Nested Loops

This kind of control statement is used in loops. For example, we may use the break statement in a loop to exit the loop. When we use a break statement inside a loop, the remaining iterations are skipped, ending the loop. 

Here is an example of this. 

# Running outer loop from 2 to 3
for i in range(2, 4):

	# Printing inside the outer loop
	# Running inner loop from 1 to 10
	for j in range(1, 11):
	if i==j:
 break
	# Printing inside the inner loop
	print(i, "*", j, "=", i*j)
	# Printing inside the outer loop
	print()

Continue Statement In Nested Loops

Another loop control statement is a continue statement. It is the break statement’s exact opposite. While the break statement ends the loop, the continue statement causes the loop to move on to the next iteration. 

Here is an example for better understanding. 

# Running outer loop from 2 to 3
for i in range(2, 4):

	# Printing inside the outer loop
	# Running inner loop from 1 to 10
	for j in range(1, 11):
	if i==j:
 continue
	# Printing inside the inner loop
	print(i, "*", j, "=", i*j)
	# Printing inside the outer loop
	print()

Instead of using a break statement in the code above, we are utilizing a continue statement. 

The result shows that “2 * 2 = 4” and “3 * 3 = 9” are not written because, at that time, “i” becomes equal to “j,” which causes the inner loop to skip the remaining code and go to the next iteration.

Single Line Nested Loops Using List Comprehension

We will use list comprehension in Python to reduce the multiline nested loops to a single line. Then for loop and brackets with an expression performed for each entry are included in the list comprehension.

Here is the syntax of the comprehensive list: 

newList = [ expression(element) for element in oldList if condition ] 

And here is an example: 

# Using list comprehension to make
# nested loop statement in single line.
list1 = [[j for j in range(3)]
 for i in range(5)]
# Printing list1
print(list1)

In the code above, we are using list comprehension in the inner loop [j for j in range(3)] to store a list within the list and create a list [0, 1, 2] for each iteration of the outer loop “for I in range(5)”.

That’s it!

Hopefully, you now know how to replace nested for loops in Python, and you found out about a thing or two about nested loops. Cheers!

Advertising links are marked with *. We receive a small commission on sales, nothing changes for you.