Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

389
Views
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?

over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

Here's a trick to see which k uses the original/modified list by printing x and k in the generator expression:

1st k refers to the original list:

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

2nd k refers to the modified list:

>>> k = [1,8,15]
>>> g = (x for x in k if (print(k) == None and k.count(x)>0))
>>> k = [2,8,22]
>>> list(g)
[2, 8, 22]
[2, 8, 22]
[2, 8, 22]
over 4 years ago · Santiago Trujillo Report

0

Debugging trick similar to Shawn's:

def p(label, x):
    print(label, x)
    return x

k = [1,8,15]
g = (x for x in p('iterate over', k) if p('count in', k).count(x)>0)
k = [2,8,22]
print('between generator construction and consumption')
list(g)

Output (Try it online!):

iterate over [1, 8, 15]
between generator construction and consumption
count in [2, 8, 22]
count in [2, 8, 22]
count in [2, 8, 22]
over 4 years ago · Santiago Trujillo Report

0

Generator is fetch on process memory,work like lazy operator so that happen

"""""for x in [1,8,15]: if [2,8,22].count(x): """" That is how interpreter fetch values.

Refer this tweet for more understand:

https://twitter.com/nedbat/status/1503735148378001410?t=lJLT482Vmt19cBNuP-PAWQ&s=19

https://twitter.com/driscollis/status/1503366898234404866?t=OgCM0E1rzWAEQOOziO9uqA&s=19

#Learning with hope

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!