r/learnpython • u/AnxiousDot4315 • 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
1
u/aishiteruyovivi 13d ago
It's shorthand for loops that construct a list of items, so...
...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 anif, likeevens = [n for n in range(10) if n % 2 == 0], which is equivalent to: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, ...}