Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80391

Re: Different behaviour in list comps and generator expressions

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: Different behaviour in list comps and generator expressions
Date 2014-11-07 23:39 -0500
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-E5EC13.23390507112014@news.panix.com> (permalink)
References <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com>

Show all headers | View raw


In article <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python@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 []
> 
> But:
> 
> [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.

Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Different behaviour in list comps and generator expressions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-11-08 12:50 +1100
  Re: Different behaviour in list comps and generator expressions Roy Smith <roy@panix.com> - 2014-11-07 23:39 -0500
  Re: Different behaviour in list comps and generator expressions Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2014-11-08 22:31 +0100
  Re: Different behaviour in list comps and generator expressions Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2014-11-08 23:42 +0100
  Re: Different behaviour in list comps and generator expressions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-11-18 10:30 +1100
    Re: Different behaviour in list comps and generator expressions Dan Stromberg <drsalists@gmail.com> - 2014-11-17 15:38 -0800
    Re: Different behaviour in list comps and generator expressions Ethan Furman <ethan@stoneleaf.us> - 2014-11-17 18:20 -0800

csiph-web