Different behaviour in list comps and generator expressions
roy at panix.com
Sat Nov 8 05:39:35 CET 2014
In article <545d76fe$0$12980$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> 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?
Wow, that's really esoteric. I can't imagine this happening in
real-life code (but I'm sure somebody will come up with an example :-))
My inclination is that a list comprehension should stop if StopIteration
is raised by the comprehension body. I can't come up with a good
argument to support that, other than it seems like the right thing to do.
More information about the Python-list