상세 컨텐츠

본문 제목

Generator basics (yield)

Coding/잡동사니

by 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]

'Coding > 잡동사니' 카테고리의 다른 글

python zip function  (0) 2021.06.29
Handling JSON files  (0) 2021.06.24
Jupyter Notebook Tutorial  (0) 2021.06.23
Deep Learning AI Course 4  (0) 2021.06.23
Linux commands  (0) 2021.06.22

관련글 더보기