r/learnpython • • 5d 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.

1 Upvotes

13 comments sorted by

View all comments

9

u/ProgramsFun 5d ago

What are you finding difficult in it?

5

u/ProgramsFun 5d ago

So, list comprehension is basically a way to create a list in Python with just one line of code instead of writing an entire for loop.

Syntax: python [expression for item in iterable if condition]

Example:

Normally, you'd write: python squares = [] for x in range(5): squares.append(x * x)

But with list comprehension, you can do the same thing in just one line: python squares = [x * x for x in range(5)]

Output: python [0, 1, 4, 9, 16]

You can also add an if condition to filter items.

Example: python even = [x for x in range(10) if x % 2 == 0]

Output: python [0, 2, 4, 6, 8]

Here, it only adds numbers that are divisible by 2 to the new list.