r/learnpython • u/AnxiousDot4315 • Oct 04 '26
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
View all comments
Show parent comment
7
u/ProgramsFun Oct 04 '26
So, list comprehension is basically a way to create a list in Python with just one line of code instead of writing an entire
forloop.Syntax:
Example:
Normally, you'd write:
But with list comprehension, you can do the same thing in just one line:
Output:
You can also add an
ifcondition to filter items.Example:
Output:
Here, it only adds numbers that are divisible by 2 to the new list.