[Python] Iterator/Generator/Coroutine

Rex Chiang
2 min readJan 12, 2022

Iterator

  • An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
  • An iterator is an object which implements the iterator protocol, which consist of the methods __iter__ and __next__.
  • Strings, lists, tuples, dictionaries, and sets are all iterable objects.
L = ["A", "B", "C"]
my_iter = iter(L)

print(next(my_iter)) # A
print(next(my_iter)) # B
print(next(my_iter)) # C
print(next(my_iter)) # StopIteration

Generator

  • Generator functions allow you to declare a function that behaves like an iterator.
  • If a function contains at least one yield statement, it becomes a generator function.
  • yield statement pauses the function, and saves all its states for later continues from there.
def my_generator(num):
for n in range(num):
yield n

return "END!"

gen = my_generator(3)

print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # StopIteration: END!

Coroutine

  • Coroutines have many entry points for suspending and resuming execution.
  • Coroutine can suspend its execution, then transfer control to other coroutine and can resume again execution from the point it left off.
  • Coroutine can input data, and send it to another coroutine for extra processing.
def my_coroutine1(a):
print("Start : a = ", a)
b = yield a
print("Recieved : b = ", b)
c = yield a + b
print("Received : c = ", c)

return "END!"

coro = my_coroutine1(1)

print(next(coro)) # Start : a = 1
# 1

print(coro.send(2)) # Recieved : b = 2
# 3

print(coro.send(3)) # Recieved : c = 3
# StopIteration: END!

def my_coroutine2(n):
ret = yield from my_coroutine1(n)
print("Return From Coroutine1 : ", ret)

return ret

coro = my_coroutine2(1)

print(next(coro)) # Start : a = 1
# 1

print(coro.send(2)) # Recieved : b = 2
# 3

print(coro.send(3)) # Recieved : c = 3
# Return From Coroutine1 : END!
# StopIteration: END!

--

--