Coding/잡동사니
Generator basics (yield)
linguana
2021. 7. 1. 12:03
##################
def sq_nums(nums):
for i in nums:
yield (i+i)
###################
my_nums = sq_nums([1,2,3,4,5])
for num in my_nums:
print(num)
2 4 6 8 10
# This is different from casting with list
my_nums = (x * x for x in [1,2,3,4,5])
print(my_nums)
<generator object <genexpr> at 0x7f9309bbd4d0>
# This would damage the performance in terms of speed and memory
my_nums2 = [x * x for x in [1,2,3,4,5]]
print(my_nums2)
[1, 4, 9, 16, 25]