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


Groups > comp.lang.python > #64744

Re: should I transfer 'iterators' between functions?

From Peter Otten <__peter__@web.de>
Subject Re: should I transfer 'iterators' between functions?
Date 2014-01-25 14:32 +0100
Organization None
References <6ad4232c-a8d9-4195-9edd-65c0e35923a7@googlegroups.com> <lc0c9l$qn5$2@ger.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.5976.1390656750.18130.python-list@python.org> (permalink)

Show all headers | View raw


Ned Batchelder wrote:

> On 1/25/14 1:37 AM, seaspeak@gmail.com wrote:
>> take the following as an example, which could work well.
>> But my concern is, will list 'l' be deconstructed after function return?
>> and then iterator point to nowhere?
>>
>> def test():
>>      l = [1, 2, 3, 4, 5, 6, 7, 8]
>>      return iter(l)
>> def main():
>>      for i in test():
>>          print(i)
>>
>>
> 
> One more thing: there's no need to call iter() explicitly here.  Much
> more common than returning an iterator from a function is to return an
> iterable.  Your code will work exactly the same if you just remove the
> iter() call:
> 
>      def test():
>          l = [1, 2, 3, 4, 5, 6, 7, 8]
>          return l
>      def main():
>          for i in test():
>              print(i)
 
For that specific client code, yes. In the general case the difference 
matters. Iteration over an iterable starts at the beginning while iteration 
over an iterator starts at the current item:

>>> def main():
...     items = test()
...     print(list(zip(items, items)))
... 
>>> def test(): return range(6) # an iterable
... 
>>> main()
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
>>> def test(): return iter(range(6)) # an iterator
... 
>>> main()
[(0, 1), (2, 3), (4, 5)]
 

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


Thread

should I transfer 'iterators' between functions? seaspeak@gmail.com - 2014-01-24 22:37 -0800
  Re: should I transfer 'iterators' between functions? Chris Angelico <rosuav@gmail.com> - 2014-01-25 17:43 +1100
  Re: should I transfer 'iterators' between functions? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-25 06:45 +0000
  Re: should I transfer 'iterators' between functions? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-25 07:55 -0500
  Re: should I transfer 'iterators' between functions? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-25 07:56 -0500
  Re: should I transfer 'iterators' between functions? Peter Otten <__peter__@web.de> - 2014-01-25 14:32 +0100

csiph-web