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


Groups > comp.lang.python > #100128

Re: Help on for loop understanding

From Erik <python@lucidity.plus.com>
Newsgroups comp.lang.python
Subject Re: Help on for loop understanding
Date 2015-12-08 01:53 +0000
Message-ID <mailman.43.1449539676.12405.python-list@python.org> (permalink)
References <f9ae2857-2ae2-4fe2-8547-d57e5ebe1fe5@googlegroups.com> <n45atn$2qs$1@news.albasani.net> <e3bc494d-6a2d-4624-adb2-add96a0f9883@googlegroups.com> <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com>

Show all headers | View raw


Hi Robert,

On 08/12/15 01:39, Robert wrote:
>> I don't find a way to show __next__ yet.
>> Can we explicitly get the iterator for a list?
>> Thanks,
>
> Excuse me. I find it as the following:
>
> xx.__iter__().next
> Out[16]: <method-wrapper 'next' of listiterator object at 0x0000000008B38AC8>
>
> xx.__iter__().next()
> Out[17]: 1

Robin has told you how things work under the hood for the particular 
version of Python that he is running (Python 3). As you've seen, it 
works a bit different under the hood in your version (Python 2).

This is why you should not be calling the __ ("dunder") methods 
directly. Until you understand more and want to write your own classes 
that support being iterated using the 'for' keyword, you should probably 
ignore them.

Instead, the way to do this which works on all versions is:

x = [1, 2, 3, 4]

xit = iter(x)
next(xit)
next(xit)
next(xit)
next(xit)
next(xit)

This is what the 'for' keyword is doing for you - it first gets an 
iterator for the list (using iter()) and then processes each element 
that the iterator returns (from next()) until it raises the exception. 
It then suppresses the exception (so you don't have to catch it 
yourself) and exits the for loop.

Of course, it might actually do this using the __ methods and other 
things as a shortcut internally, but that's just an implementation detail.

E.

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


Thread

Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:05 -0800
  Re: Help on for loop understanding Robin Koch <robin.koch@t-online.de> - 2015-12-08 02:14 +0100
    Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:31 -0800
      Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:39 -0800
        Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:50 -0800
          Re: Help on for loop understanding Erik <python@lucidity.plus.com> - 2015-12-08 02:36 +0000
          Re: Help on for loop understanding Chris Angelico <rosuav@gmail.com> - 2015-12-08 14:23 +1100
            Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-08 06:59 -0800
        Re: Help on for loop understanding Erik <python@lucidity.plus.com> - 2015-12-08 01:53 +0000

csiph-web