Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Eh, while comprehensions with multiple for-ins push the limits of good taste, I don't think:

    planets_set = {
        planet for episode in episodes.values() 
        for planet in episode['planets']
    }
is less maintainable in a Python shop than say...

    planets = set()

    for episode in episodes.values():
        planets.update(episode['planets'])
Although the latter will likely make perfect sense to most non-python developers. The former is faster and has a smaller memory footprint and might be preferred when dealing with a larger or more irregular data sets.

The former also has the advantage of not leaking the "episode" variable into the function/method scope, which could introduce a subtle bug if that variable gets conditionally reused. So while it's harder to understand for a less-experienced python developer, the set comprehension solution is inherently safer due to python's design.



Additionally, generator comprehensions can be far more efficient than any simple for loop. If you had a generator with a billion star coordinates being read from some file, you'd never be able to load it all into memory. So, instead of manually making a generator function, you could just do

    coordinates = (star.x, star.y, star.z for star in star_map)


Though in py2 list comprehensions do leak scope. (dict comprehensions don't, you are correct on that :).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: