vipnoob
vipnoob

Reputation: 1

How does iter() convert the list into the iterator object?

I know that an iter() function converts the list (or another collection) to iterator object. But I can't exactly understand what an iterator object is.

I read that it's unordered data, every element of that (after calling __next__()) assigned to local variable.But how does computer know which element of the iterator will be next?

Upvotes: 0

Views: 539

Answers (2)

user14781663
user14781663

Reputation:

Iterator object store these info in its fields. Like this (we will assume that our array use normal indexing) :

class IteratorObject:
    def __init__(self, iterated_array) :
        self.iterated = iterated_array 
        self.current_index = 0 # starting index is 0

    def __iter__(self) :
        return self # there isnt reason to create new iterator object - we will return existing one

    def __next__(self) :
        #if current_index is bigger that length of our array, we will stop iteration
        if self.current_index >= len(self.iterated):
            raise StopIteration() #this is exception used for stopping iteration
   
        old_index = self.current_index
        self.current_index += 1

        return self.iterated[old_index

You can see that iterator object has inner field that store current index (current_index). And if this index is bigger than length of iterated array, we will end iteration(using StopIteration exception).

You can implement iterator in any way you want. Like you can have iterator that will iterate from the end to the start of array - you just need tostart with last index and end with 0 index.

Tl;dr: iterator is object and like every object, it has fields. And iterator use these fields to store information about iteration

Upvotes: 1

jp_
jp_

Reputation: 87

an iterator(object with __iter__ method) can be used in iter(). there are two ways something gets itered.

  1. iter returning an iter. when iter() gets called, it returns an already iterd list(when you iter() a list) this will keep going until the itered object has is a builtin object, wich can actually make it's own iter.

Upvotes: 0

Related Questions