FAQ: Learn Python: Loops - More List Comprehensions

In Python, most certainly. It is a very useful mapping tool and once you get more into using it you’ll find all manner of usage cases. The enclosed for is non-breaking, which means it runs through the entire iterable. However we can include a conditional expression to limit what values get added to the output list.

Used as a filter:

a = [44, 54, 64, 48, 49, 61, 57, 60, 51]

b = [x for x in a if x > 48]

print (b)

>>> [54, 64, 49, 61, 57, 60, 51]

Used as a map:

c = [x * 2 for x in a]

print (c)

>>> [108, 128, 98, 122, 114, 120, 102]

What’s more, we can nest for loops:

b = [2, 3, 5, 7]
x = [2, 3, 4, 5]

y = [a ** n for a in b for n in x]

print (y)

>>> [4, 8, 16, 32, 9, 27, 81, 243, 25, 125, 625, 3125, 49, 343, 2401, 16807]

and even nest comprehensions. Care to give that a try?

1 Like

I’m amazed by how fast your response was! The way you broke this down makes a lot more sense now. Thank you!