rpb
rpb

Reputation: 3299

List comprehension IF OR Condition

When evaluate the x != '0' or x != '-1', the compiler return the intended output.

opt=[f'xt:{x}' for x in status if x != '0']

OR

opt=[f'xt:{x}' for x in status if  x !='-1']

The issue arise when I combine the x != '0' or x !='-1' together.

status = ['-1', '2', '3', '0']
opt=[f'xt:{x}' for x in status if x != '0' or x !='-1']
['xt:-1', 'xt:2', 'xt:3', 'xt:0']

But, I expect the output to be

opt=['xt2','xt3']

Upvotes: 0

Views: 54

Answers (2)

boss
boss

Reputation: 1

It will work if you switch the 'or statement' to an 'and statement' because the 'or statement' always evaluates to true in this case.

Upvotes: 0

Cole Henrich
Cole Henrich

Reputation: 165

It should be x != '0' **and** x !='-1'. I know what you mean in "humanspeak"- neither 0 nor -1, but for a computer, that's "not 0, or not -1". So -1 is ok, because it's not 0, and the computer is satisfied. So all you need to do is change that or to an and.

Upvotes: 2

Related Questions