Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lisp-style style `let` syntax in Python list-comprehensions

Consider the following code:

>>> colprint([
        (name, versions[name][0].summary or '')
        for name in sorted(versions.keys())
    ])

What this code does is to print the elements of the dictionary versions in ascending order of its keys, but since the value is another sorted list, only the summary of its first element (the 'max') is printed.

Since I am familiar with let from lisp, I rewrote the above as:

>>> colprint([
        (name, package.summary or '')
        for name in sorted(versions.keys())
        for package in [versions[name][0]]
    )]

Do you think this violates being Pythonic? Can it be improved?

Note: For the curious, colprint is defined here.

like image 309
Sridhar Ratnakumar Avatar asked Dec 15 '09 20:12

Sridhar Ratnakumar


3 Answers

Why not exploit tuples?

colprint([(name, version[0].summary or '')
      for (name, version) in sorted(versions.iteritems())])

or, even

colprint(sorted([(name, version[0].summary or '')
             for (name, version) in versions.iteritems()]))

Also, you may consider (in my first example) removing the []s, because that way you get a generator instead of a list (which may or may not be useful, since I'm guessing this'll print the whole array, so you won't be saving any evaluations).

like image 111
Tordek Avatar answered Oct 09 '22 09:10

Tordek


I wouldn't use the "tricky for clause" (or "let-equivalent") in most cases, but I would if it's the natural way to avoid repetition, especially costly repetition. E.g.

xs = [(y, y*1.2, y-3.4) for z in zs for y in [somefun(z)] ]

looks much better to me than calling somefun three times!-) So, it's worth keeping in mind, even if probably not worth using where it does not remove repetition.

like image 24
Alex Martelli Avatar answered Oct 09 '22 09:10

Alex Martelli


So you're using "for x in [y]" as a substitute for "let x y".

Trying to emulate language's syntax in another language is never a good idea. I think that the original version is much clearer.

like image 44
Amnon Avatar answered Oct 09 '22 09:10

Amnon