Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

# generators

# generators
gen_1= (x*x for x in [1,2,3])   # [1, 4, 9]
gen_2 = (x+x for x in gen_1)  # [2, 8, 18]
for i in gen_2:
   print(i)

# 2
# 8
# 18
 
for i in gen_1:
   print(i)


# Nothing is displayed
# With generators, instead of storing data in the variable gen_1 (and therefore in memory), you are going to generate them on the spot (e.g. only when you need them).
# Careful: Generating data on the spot does not allow to read them several times. And if you try to do so, no error will be raised to warn you.
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #generators
ADD COMMENT
Topic
Name
1+8 =