#################################################################### #################################################################### ### 1. Iterators #################################################################### #################################################################### #################################### ## Several built-in iterable types: ## list, str, dict, set, tuple #################################### """ l = [1,3,2] li = iter(l) li #list_iterator object next(li) next(li) next(li) next(li) #raises StopIteration for e in l: #new iterator created here print(e) #for knows to "swallow" StopIteration """ #################################################################### #################################################################### ### 2. Generators #################################################################### #################################################################### def countdown_gen(): ''' calling it creates an iterator for the values 5,4,3,2,1,'launch' ''' yield 5 yield 4 yield 3 yield 2 yield 1 yield 'launch' # a function which produces a list of all positive even numbers up to n def Evens_list(n): ''' a list of evens up to n ''' return [num for num in range(n) if num%2==0] # a generator function (includes a "yield" statement) which produces a generator that generates # all positive even numbers up to n def Evens_gen(n): ''' a generator of evens up to n ''' for i in range(n): if i%2 == 0: yield i # A function that produces a generator using a generator expression. # The generator is exactly the same as the one produces by Evens_gen def Evens_gen2(n): ''' a generator of evens up to n ''' return (num for num in range(n) if num%2==0) # a generator which produces the **infinite** sequence of all positive even numbers def All_evens_gen(): i=0 while True: yield i i+=2 ###You may open task manager and watch memory/CPU usage """ l = Evens_list(10**8) #memory up for x in l: pass del l #memory down l = Evens_gen(10**8) #memory stays down all the time for x in l: pass del l """