Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #26504
| Date | 2012-08-04 21:11 +0100 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: when an iterable object is exhausted or not |
| References | <franck-DC86E6.21203604082012@news.free.fr> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2947.1344111131.4697.python-list@python.org> (permalink) |
On 04/08/2012 20:20, Franck Ditter wrote: > Two similar iterable objects but with a different behavior : > > $$$ i = range(2,5) > $$$ for x in i : print(x,end=' ') > > 2 3 4 > $$$ for x in i : print(x,end=' ') # i is not exhausted > > 2 3 4 > > --------- Compare with : > > $$$ i = filter(lambda c : c.isdigit(), 'a1b2c3') > $$$ for x in i : print(x,end=' ') > > 1 2 3 > $$$ for x in i : print(x,end=' ') # i is exhausted > > $$$ > > IMHO, this should not happen in Py3k. > What is the rationale of this (bad ?) design, which forces the programmer > to memorize which one is exhaustable and which one is not ?... > 'range' returns a 'range' object: >>> i = range(2,5) >>> i range(2, 5) The 'for' loop passes it to 'iter' to get an iterator: >>> iter(i) <range_iterator object at 0x0135DB30> More importantly: >>> iter(i) is i False In other words, when asked for an iterator, the 'range' object always creates a new one. On the other hand, 'filter' returns a 'filter' object: >>> i = filter(lambda c : c.isdigit(), 'a1b2c3') >>> i <filter object at 0x01360B30> The 'for' loop passes it to 'iter' to get an iterator: >>> iter(i) <filter object at 0x01360B30> More importantly: >>> iter(i) is i True In other words, the 'filter' object returns _itself_ as the iterator.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
when an iterable object is exhausted or not Franck Ditter <franck@ditter.org> - 2012-08-04 21:20 +0200
Re: when an iterable object is exhausted or not Tim Roberts <timr@probo.com> - 2012-08-04 12:44 -0700
Re: when an iterable object is exhausted or not Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-05 00:47 +0000
Re: when an iterable object is exhausted or not MRAB <python@mrabarnett.plus.com> - 2012-08-04 21:11 +0100
Re: when an iterable object is exhausted or not Tim Chase <python.list@tim.thechases.com> - 2012-08-04 15:24 -0500
Re: when an iterable object is exhausted or not Terry Reedy <tjreedy@udel.edu> - 2012-08-04 17:04 -0400
Re: when an iterable object is exhausted or not Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-05 02:13 +0000
csiph-web