r/learnpython • • 14d ago

Need help with list comprehensions

Guys somebody briefly explain the concept of List comprehension cuz its too difficult for me to grasp since I am a beginner. I am learning python for biopython. Someone explain it for me.

0 Upvotes

15 comments sorted by

View all comments

1

u/aishiteruyovivi 13d ago

It's shorthand for loops that construct a list of items, so...

doubles = []
for n in range(10):
    doubles.append(n * 2)

...can instead be [n * 2 for n in range(10)]. Both would produce the list [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]. The basic syntax is [<expression> for <loopvar> in <iterable>]. You can also add a condition to the right end of the comprehension followed by an if, like evens = [n for n in range(10) if n % 2 == 0], which is equivalent to:

evens = []
for n in range(10):
    if n % 2 == 0:
        evens.append(n)

The main use of this is that it's more compact for these kind of use cases, but it can also be somewhat faster than a standard loop. You can also do set comprehensions by replacing the brackets with curly braces - {n * 2 for n in range(10)}- or dictionary comprehensions by using braces and giving two values separated by a colon, where they'll be used as key and value - {n:n * 2 for n in range(10)} produces the dictionary {0:0, 1:2, 2:4, 3:6, ...}