Skip to content

List comprehension Python for loop | Example code

  • by

Using for loop with List comprehension work as a Nested Loops in Python.

Note: The nested loops in list comprehension don’t work like normal nested loops.

Example List comprehension Python for loop

Simple example code list comprehension for loop and if to find the transpose of the matrix.

matrix = [[1, 2], [3, 4], [5, 6]]
transpose = [[row[i] for row in matrix] for i in range(2)]

print(transpose)

Output:

List comprehension Python for loop

Do comment if you have any doubts and suggestions on this Python list tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *