Different behaviour in list comps and generator expressions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 8 02:50:53 CET 2014

The following list comprehension and generator expression are almost, but
not quite, the same:

[expr for x in iterable]

list(expr for x in iterable)

The difference is in the handling of StopIteration raised inside the expr.
Generator expressions consume them and halt, while comprehensions allow
them to leak out. A simple example:

iterable = [iter([])]
list(next(x) for x in iterable)
=> returns []


[next(x) for x in iterable]
=> raises StopIteration

Has anyone come across this difference in the wild? Was it a problem? Do you
rely on that difference, or is it a nuisance? Has it caused difficulty in
debugging code?

If you had to keep one behaviour, which would you keep?


More information about the Python-list mailing list