Generator works weird

a = [1, 2, 3]
b = (c for c in a if c in a)
a = [2, 3, 4]
print(list(b))


def d(expr):
    for c in expr:
        if c in expr:
            yield c


a1 = [1,2,3]
t = d(a1)
a1 = [2,3,4]
print(list(t))

conclusion:

[2, 3]
[1, 2, 3]

Question: 1) in the first version, the loop keeps the old value of the list ([1,2,3]), but the conditional expression takes the new list a ([2,3,4]). 2) how does my own generator give me a different result than the generative expression?

For example, I replaced a on the real lists of the first example, I hope this becomes more clear my first question.

a = [1, 2, 3]
b = (c for c in [1,2,3] if c in [2, 3, 4])
a = [2, 3, 4]
print(list(b))

Conclusion:

[2,3]
+4
source share
1 answer

According to PEP 289 , we can rewrite the expression of your generator as follows:

# b = (c for c in a if c in a)

def __gen(expr):
    for c in expr:
        if c in a:
            yield c
b = __gen(iter(a))

Here the link to [1, 2, 3]for use in the for loop is fixed immediately (upon creation b), but the test if c in auses a new global one a, which is equal to [2, 3, 4].

, , a1 for if x in y. a1 = [2, 3, 4] .

, , , , if c in expr if c in a1.

+3

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


All Articles