Using an iterator function to build a list

PHOTO EMBED

Mon Mar 30 2020 12:18:27 GMT+0000 (Coordinated Universal Time)

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])]
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40,
content_copyCOPY

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.

https://www.30secondsofcode.org/python/s/unfold/