Python Forum
why the generator expression after IF always returns True
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why the generator expression after IF always returns True
#1
Hi,

Why is the generator expression after IF statement always return True? Is it because the if statement only checks whether there is a new value "generated" by the expression, if so, then it will return True? But the below expression (a>100 for in x) will not generate a new value, will it?

For example:

x=[1,2,3,4,5]
y=[a**2 for a in x if (a>100 for a in x)]
print(y)
The result is
[1, 4, 9, 16, 25]
Thanks in advance!
Reply
#2
from the docs
Quote:In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
https://docs.python.org/3/reference/expressions.html
generator is an object, not empty container.
also question on SO
https://stackoverflow.com/questions/7976...-exhausted

all that said, your code does not make lot of sense. what do you want to achieve?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is the following code returning a generator expression? quazirfan 8 1,596 Apr-11-2023, 11:44 PM
Last Post: quazirfan
  Recursive function returns None, when True is expected akar 0 3,374 Sep-07-2020, 07:58 PM
Last Post: akar
  Pass results of expression to another expression cmdr_eggplant 2 2,271 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  Substitution with regular expression returns hidden character SOH bajacri 2 3,801 Nov-17-2019, 03:38 AM
Last Post: bajacri
  Returning True or False vs. True or None trevorkavanaugh 6 9,216 Apr-04-2019, 08:42 AM
Last Post: DeaD_EyE
  os.path.isdir(<whatever>) returns always True Fabrizio 3 4,672 Dec-04-2018, 04:28 PM
Last Post: nilamo
  Python returns generator instead of None Tawnwen 4 4,668 Mar-09-2018, 07:06 AM
Last Post: DeaD_EyE
  receive from a generator, send to a generator Skaperen 9 5,475 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020