Home > Net >  Iteration Functionality
Iteration Functionality

Time:10-07

Below is the simple programme which I wrote in Python

Animal = ['tiger','lion','dog','cat']
xyz = iter(Animal)
print(next(xyz))

The output was

tiger

Now I read that iter() method points towards the first element of iterable i.e 'tiger', so the second line will make xyz pointing towards 'tiger' & then in third line when I use next it should go to 'lion' and print that why is it not doing so?

I know there is some conceptual mistake which I am doing & I am even not able to comprehend that whether xyz or iterators are variable object or something else. Can anyone please elaborate?

CodePudding user response:

You are slightly confused.

Think of next() as "give the current value and then move the pointer to the next item." Line numbers have nothing to do with it. The next time you called next(xyz), you'd get 'lion' no matter where it occurs.

CodePudding user response:

iter() doesn't "point towards the first element of the iterable", it just returns an iterator.

>>> xyz
<list_iterator object at 0x7f56c61eb3c8>

You could, for example, turn it back into a list:

>>> xyz = iter(Animal)
>>> list(xyz)
['tiger', 'lion', 'dog', 'cat']

But unlike a list, it can only be consumed once.

>>> list(xyz)
[]

CodePudding user response:

Note that iter and next do exactly what the docs say they do, so this code:

Animal = ['tiger','lion','dog','cat']
xyz = iter(Animal)
for i in range(len(Animal)   1):
    print(next(xyz))

prints all animals from first to last until the iterator is exhausted:

tiger
lion
dog
cat
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print(next(xyz))
StopIteration
  • Related