# Nested for Loop in One Line in Python

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:

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:

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 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.