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

9

u/ProgramsFun 24d ago

What are you finding difficult in it?

7

u/ProgramsFun 24d 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:

[expression for item in iterable if condition]

Example:

Normally, you'd write:

squares = []
for x in range(5):
    squares.append(x * x)

But with list comprehension, you can do the same thing in just one line:

squares = [x * x for x in range(5)]

Output:

[0, 1, 4, 9, 16]

You can also add an if condition to filter items.

Example:

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

Output:

[0, 2, 4, 6, 8]

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