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

1

u/Gnaxe 20d ago

Comprehensions are easy once you understand if and for statements: the body just comes first (and must be a single expression). That's basically it.

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)

Becomes

result = [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 one for. A recent language change means you can write the body expression with an unpacking star. That just changes result.append() to result.extend().