yield seq def scramble(seq)for in range(len(seq))yield seq[ :seq[:ilist(scramble('spam')['spam''pams''amsp''mspa'list(scramble(( ))[( )( )( )for in scramble(( ))print(xend='generator function assignments work here generator function yield one item per iteration list()generates all results any sequence type works for loops generate results ( ( ( generator functions retain their local scope state while activeminimize memory space requirementsand divide the work into shorter time slices as full functionsthey are also very general importantlyfor loops and other iteration tools work the same whether stepping through real list or generator of values--the function can select between the two schemes freelyand even change strategies in the future generator expressions as we've seengenerator expressions--comprehensions in parentheses instead of square brackets--also generate values on request and retain their local state they're not as flexible as full functionsbut because they yield their values automaticallyexpressions can often be more concise in specific use cases like thiss 'spamg ( [ : [:ifor in range(len( ))list( ['spam''pams''amsp''mspa'generator expression equivalent notice that we can' use the assignment statement of the first generator function version herebecause generator expressions cannot contain statements this makes them bit narrower in scopein many casesthoughexpressions can do similar workas shown here to generalize generator expression for an arbitrary subjectwrap it in simple function that takes an argument and returns generator that uses itf lambda seq(seq[ :seq[:ifor in range(len(seq)) (sat list( ( )['spam''pams''amsp''mspa'list( ([ ])[[ ][ ][ ]for in (( ))print(xend='generator functions and expressions