Using an iterator function to build a list


Mon Mar 30 2020 12:18:27 GMT+0000 (UTC)

Saved by @bambifruit #python #python #iterator #functions

#In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists.
# define function:
1.def unfold(fn, seed):
  2.def fn_generator(val):
    3.while True: 
      4.val = fn(val[1])
     5.-5 if val == False: break
      6.yield val[0]
  7.return [i for i in fn_generator([None, seed])]
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40,

Iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. In Python, an iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods.