for loop in a sequence or in an iterator

Viewed 94

I have 3 object Item1, Item2 and a custom iterator. Item2 is same as Item1 but it implements one more function __iter__() than Item1, __iter__() will return a custom iterator.

class Item1():
    def __init__(self, stop):
        self.stop = stop

    def __len__(self):
        return self.stop - 1

    def __getitem__(self, index):

        if index < self.stop:
            return index + 1
        raise IndexError


class Item2():
    def __init__(self, stop):
        self.stop = stop

    def __len__(self):
        return self.stop - 1

    def __getitem__(self, index):

        if index < self.stop:
            return index + 1
        raise IndexError

    def __iter__(self):
        iterator = MyIterator(self.stop)
        return iterator


class MyIterator:
    def __init__(self, max_num):
        self.max_num = max_num
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        if self.index <= self.max_num:
            return self.index
        else:
            raise StopIteration

When I use for loop to iterate Item1 and Item2, will get same results. But, I want to know the usage of memory will be the same ? Does the Item2 have the advantage of iterator?

Item1 = Item1(100000)
item2 = Item2(100000)

for item in item1:
    print(item)

for item in item2:
    print(item)
1 Answers
Related