Home > Enterprise >  why here do we get 4 objects instead of 3? because I have only 3 elements in my list
why here do we get 4 objects instead of 3? because I have only 3 elements in my list

Time:10-08

why here do we get 4 objects instead of 3? because I have only 3 elements in my list

def special_for(iterable):
    iterator = iter(iterable)
    while True:
        try:
            # print(next(iterator))
            print(iterator)
            next(iterator)
        except(StopIteration):
            break


my_arr = [1, 2, 3]
special_for(my_arr)

And the output is :

<list_iterator object at 0x107a67e50>
<list_iterator object at 0x107a67e50>
<list_iterator object at 0x107a67e50>
<list_iterator object at 0x107a67e50>

CodePudding user response:

The script prints the address of the iterator and not the elements of the iterable and this is done before calling next. print is then called four times before next that will raise an exception the fourth time it is called (iterator is then exhausted - pointing to nothing). Look at your console output, print prints out an address in the form of 0x... and not the element itself.

Here is an example that prints out the elements of the iterable

def iter_and_print(iterable):
    iterator = iter(iterable)
    while True:
            try:
                    print(next(iterator))
            except StopIteration:
                    break
iter_and_print([1, 2, 3])

Output:

1
2
3

CodePudding user response:

This is answered by the comments, but it is just a simple bug that the print occurs before the next raises the StopIteration. In the future, I would recommend actually printing your items, rather than the iterator instance itself, which should have made the issue more obvious. It would have run: 1, 2, 3, (exception)

  • Related