Print out n elements of a list each time a function is run

A common approach is a generator expression. A generator expression yields it value when it is needed and hence, the whole list would not be created at once

A solution to your problem might be this

book1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']

def yield_book(book1):
    for i in book1:
        yield i;
                
def print_n_item(gen, n):
    count = 0
    for i in gen:
        if count == n:
            return
        print(i)
        count += 1
        
gen = yield_book(book1)
print_n_item(gen, 5) # prints a,  b,  c, d, e
print_n_item(gen, 5) # prints f,  g,  h,  i,  j
print_n_item(gen, 5) # prints k,  l,  m,  n,  o

This approach exhausts the iterator and hence can be used once, in order to iterate again, you have to call yield_book to return a new generator


I guess you can try the following user function which applied to iterator book

def print_book(book):
    cnt = 0
    while cnt < 5:
        try:
            print(next(book))
        except StopIteration:
            print("You have reached the end!")
            break
        cnt += 1

such that

>>> bk1 = iter(book1)
>>> print_book(bk1)
a
b
c
d
e
>>> print_book(bk1)
f
g
h
i
j
>>> print_book(bk1)
k
l
m
n
o
>>> print_book(bk1)
You have reached the end!