List Comprehension is an excellent way to define a new List in just a single line.

Syntax: [function for var in iterable ]

—–> Let’s print all numbers within a given range

—–> Let’s print all numbers within a given range after adding 5 to them

—–> Let’s print all even numbers within a given range

Notice that function/expression is inserted at first place , for loop at second place and condition numbers%2==0 is inserted in the last.


List comprehension can be nested too.

Let me explain how.

Suppose we have a list of lists as-

myList = [ [11,22,33], [44,55,66], [77,88,99] ]

And I wish to print it in a flat format like this- 11, 22, 33, 44, 55, 66, 77, 88, 99.

Normally, we use following logic for implementation-

But things become Super Duper Easy when we implement using List Comprehension.

Okay so in above code, the control first is at for Lst in myList then it goes to for nums in Lst

and then it finally prints the nums . This follows exactly in the same sequence as in the code which is implemented without list comprehension.

—-> Now let’s print all Prime numbers using List Comprehension

—-> Print all Armstrong numbers within a given range

Without list comprehension-
Using List Comprehension

That’s it !

Happy Coding!

Leave a comment