Skip to content

Are list comprehensions pythonic? #167

@pbdeuchler

Description

@pbdeuchler

While I'd agree list comprehensions are generally nice, and make one feel very clever when using them, are they necessarily more pythonic than their counterparts?

In your section "Short Ways to Manipulate Lists" you call the following code "Bad",

# Filter elements greater than 4
a = [3, 4, 5]
b = []
for i in a:
    if i > 4:
        b.append(i)

and the following list comprehensions "Good",

b = [i for i in a if i > 4]
b = filter(lambda x: x > 4, a)

The section goes on to include more examples.

I would argue that calling the simpler code "Bad" simply because it takes up more space and doesn't include lambdas/one liners gives the wrong message, especially to beginners. Following the Zen of Python, specifically "Explicit is better than implicit", "Simple is better than complex", and "Readability counts" the list comprehensions could be qualified as less pythonic than the more explicit nested conditional clauses. However, this could be refuted by "Flat is better than nested".

I could be wrong, just thought I would bring it up.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions