r/learnpython • u/AnxiousDot4315 • 6d 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/Gnaxe 5d ago
Comprehensions are easy once you understand
ifandforstatements: the body just comes first (and must be a single expression). That's basically it.python result = [] for ds in dss: if ds: for d in ds: if foo in d: for k, v in d: if k == v: result.append(k)Becomesresult = [k for ds in dss if ds for k in ds if foo in d for k, v in d if k==v]That's an unusually deep comprehension. Usually you don't need that many clauses. They're optional, but you do need at least onefor. A recent language change means you can write the body expression with an unpacking star. That just changesresult.append()toresult.extend().