List comprehension Python for loop | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.