>> x = [2,3,4] >>> y = (v * 2 for v in x) >>> del x...">

Why does "del x" not change the result of the generator, but x.append does?

I can do it:

>>> x = [2,3,4] 
>>> y = (v * 2 for v in x)
>>> del x                          # x is deleted
>>> print(list(y))                 # y still exists
[4, 6, 8]

This may allow me to think that the generator y is independent of the list x. But I can also do this:

>>> a = [2, 3, 4]
>>> b = (v * 2 for v in a)
>>> a.append(5)                   # change a
>>> print(list(b))                # b is also changed
[4, 6, 8, 10]

This makes me feel like generator b is still pointing to list a. Therefore, I wonder how the generator is created. Or maybe there is something about how x is removed in the first case.

+4
source share
3 answers

del . . , - . x y (). del x, x, . x, , .

+6

.

[4, 6, 8] (x * 2 for x in <some list>) , .

, , - , . x, .

,

del x

, . (x, ), . , .

+4

x , x. :

x = [2,3,4] 
y=x
del x
print(y)

, , - .

+2

Source: https://habr.com/ru/post/1679741/


All Articles