Python

Python Iterators and Generators

brian | Published: Feb. 13, 2024, 8:48 p.m. | Updated: July 12, 2025, 1:55 a.m.

Profile Picture

 What is An Iterator in python?

An Iterator in python is an object that you can iterate over, and it contains the __next__ method. A list for example is iterable, but it is NOT an iterator. Just because something is iterable, doesn't mean that it is an iterator, for something to be considered an iterator it MUST contain the __next__ method which a list does not.

 

How can we tell if something is Iterable?

If something is iterable, that means that it can be looped over with a  for loop and it also will contain the __iter__() method. Examples of iterables include: Lists, tuples, dictionaries, and sets.

 

#lets create a simple list and loop over it 
names = ['brian', 'bob', 'rambo']

for name in names:
    print(name)



----output----
>>brian
>>bob  
>>rambo

 

Whats happening here?

the for loop is calling the __iter__ in the background on our object, and returning an iterator that we loop

 

 

 

An iterator knows where it's at beacuse it is an object with a STATE

#lets create a list with some numbers

nums = [1, 2, 3, 4, 5]

num = nums.__iter__()

print(next(num))
print(next(num))


---output---
>>1
>>2

 Whats going on here?

1. We created a list of some numbers and named it nums

2. we set a variable called num equal to nums.__iter__ which returned an iterator for us, allowing us to be able to use the next() method, because as we mentioned previously, iterators contain the __next__  dunder method

3. Now any time we call the print(next()) on the num it remembers where it left off

 

What is a Generator?

In Python, a generator is a special type of iterable that allows you to generate values  using the yield keyword. Generators are iterators, but unlike regular iterators which compute and store all values upfront, generators compute values only when needed, making them memory efficient, especially for large datasets.

  • they yield a value, when they yield that value it keeps that state until the generator is ran again and yields the next value

 

  • generators are iterators, but the __iter__ and __next__ are created automatically

 

Creating A Generator Function

def my_range(start, end):
    current = start
    while current < end:
        yield current
        current+=1

if __name__ == '__main__':
    nums = my_range(1, 5)
    
    print(next(nums))
    print(next(nums))
    print(next(nums))



---output---
>>1
>>2
>>3

 

Looping over the generator 

#looping over 
def my_range(start, end):
    current = start
    while current < end:
        yield current
        current+=1

if __name__ == '__main__':
    nums = my_range(1, 5)

    for num in nums:
        print(num)


---output---
>>1
>>2
>>3
>>4