Question:
Write a program to print the squares of the numbers in a list [1,2,3,4,5] without using any iterative function.,
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#creates generator def squaregenerator(nums): for i in nums: #yield keyword makes it a generator yield(i*i) #no need of return as it is generator #our data my_nums = [1,2,3,4,5] res2=squaregenerator(my_nums) print res2 print next(res2) print next(res2) print next(res2) print next(res2) print next(res2) <span style="color: #000000;"><strong>Explanation:</strong></span> <span style="color: #000000;">Generators are very easy to implement, but a bit difficult to understand.</span> <span style="color: #000000;">Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.</span> <span style="color: #000000;">When an iteration iterate over a set of item starts using <strong>for</strong> statement, the generator runs. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the <strong>for</strong> loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.</span> <span style="color: #000000;"><strong>Output:</strong></span> |
1 2 3 4 5 6 |
<generator object squaregenerator at 0x2ac4a8d49820> 1 4 9 16 25 |
Leave a Reply