Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python weird answer (tuple and list with count function)

This is the code given below.

k = [1, 8, 15]
g = (x for x in k if k.count(x) > 0)
k = [2, 8, 22]
print(list(g))

I am getting the output as [8] but it should be [1,8,15], right? since each element is present at least once.

Any plausible explanation for the answer?

like image 216
Sanketsz Avatar asked May 16 '26 09:05

Sanketsz


1 Answers

That's a generator expression. It creates a generator, not a tuple.

Exactly one part of a generator expression is evaluated at genexp creation time. It's this part:

g = (x for x in k if k.count(x)>0)
#               ^

Everything else, including this part:

g = (x for x in k if k.count(x)>0)
#                    ^

is evaluated lazily.

That means the k you're looping over is the original k, but the k you're calling count on is the new k.

like image 53
user2357112 supports Monica Avatar answered May 18 '26 22:05

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!