Nested for Loop in One Line in Python

Nested for Loop in One Line in Python

  1. Nested for Loop in One Line Using List Comprehension in Python
  2. Nested for Loop in One Line Using the exec() Function in Python
  3. Summary

The for loop is one of the most commonly used loops to iterate items from a list. In Python, we write the for loop in one line, but how can we write it in one line when we have to use another loop inside it?

This tutorial will discuss some different methods that can be used to write a nested for loop in just one line.

Nested for Loop in One Line Using List Comprehension in Python

There are three methods in which we can easily write a nested for loop in one line. One of them is list comprehension. It is a compact way of creating lists.

Syntax:

# python
[print(a, b) for a in listOne for b in listTwo]

Let’s go through an example and use list comprehension. First of all, we will create two lists, listOne and listTwo, and then use them to print the result as shown below.

# python
listOne = [1,3,5]
listTwo = [2,4,6]

[print(a+b) for a in listOne for b in listTwo]

Output:

Nested for Loop Example Using List Comprehension

From the example, we have added 2 different lists using the nested for loop in one line using list comprehension.

Nested for Loop in One Line Using the exec() Function in Python

Now, we will discuss another function that can help us achieve a nested for loop in one line, the exec() function. It is used for the dynamic execution of a Python program that can be a string or an object code.

Let’s go through an example in which we will add two lists and print the sum as shown below.

# python
listOne = [1,3,5]
listTwo = [2,4,6]

exec("for a in listOne:\n    for b in listTwo:\n        print(a+b)")

Output:

Nested for Loop Example Using exec() Function

As you can see from the example, using the exec() function, we added 2 different lists using nested for loop in one line.

Summary

This tutorial taught us two different methods, list comprehension and exec(), that can be used to nest for loops in one line.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Python Loop

  • Access the Index in 'Foreach' Loops in Python
  • Python While Loop User Input
  • The Next Item in Python for Loop
  • Async for Loop in Python
  • Retry a Loop in Python
  • Skip Iterations in a Python Loop