Search⌘ K

Evaluation Time Discrepancy

Discover the differences between compile-time and runtime evaluations in Python generators. Learn how generator expressions handle variable references and updates, enabling you to predict outputs and avoid common pitfalls in Python programming.

We'll cover the following...

Do the compile-time and runtime evaluations differ? Let’s find out.

1.

Let's see an example for a typical generator expression:
C++
array = [1, 8, 15]
gen = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
print(list(gen)) # Where did the other values go?

2.

Let's modify the code a bit.
C++
array_1 = [1,2,3,4]
gen_1 = (x for x in array_1)
array_1 = [1,2,3,4,5]
print(list(gen_1))
array_2 = [1,2,3,4]
gen_2 = (x for x in array_2)
array_2[:] = [1,2,3,4,5]
print(list(gen_2))

3.

Can you predict the output of the code below?

C++
array_3 = [1, 2, 3]
array_4 = [10, 20, 30]
gen = (i + j for i in array_3 for j in array_4)
array_3 = [4, 5, 6]
array_4 = [400, 500, 600]
print(list(gen))

Explanation

  • In a generator expression, the in clause is evaluated at declaration time, but the conditional clause is
...