Reputation:
I have a fundamental and basic python question. I searched in the google but I couldn't find the answer. I am wondering when I use or
in if condition
is there any way to see which part of if
condition is correct in the following example.
I have list : my= ['A','B','C']
if 'S' in my or 'T' in my or 'C' in my:
print('yes') # now I wanna know which one is correct. the answer here is `C`
Note : I know I can use for
loop over elements of my
to figure it out. I am wondering if there is a keycode for that or not.
Upvotes: 2
Views: 179
Reputation: 10152
Repetitive walrus one:
if (x := 'S') in my or (x := 'T') in my or (x := 'C') in my:
print('yes', x)
With your list it prints yes C
.
I see chepner already posted a similar one. Mine has more code repetition, but has the advantage of being lazy, evaluating only as many expressions as needed, until the first hit.
Upvotes: 1
Reputation: 11922
Since both repeated code and any
are already in other answers, I thought it would be worthwhile to give another angle as an example of a one-liner if
:
print('S' if 'S' in my else 'T' if 'T' in my else 'C' if 'C' in my else 'Nothing')
Or if you're ok with loops, a one-liner can look like this:
print([char for char in 'STC' if char in my][0]) # Would throw IndexError if not found
Upvotes: 0
Reputation: 530940
Consider the following use of any
. It would be nice if you could write
# NameError on print(x)
if any(x in my for x in ['S', 'T', 'C']):
print(x)
except x
is only in scope for the generator expression. You can, however, use an assignment expression to capture the last assignment to x
for use after any
returns.
if any((witness := x) in my for x in ['S', 'T', 'C']):
print(witness)
witness
is repeatedly set to x
; when a comparison finally succeeds, any
stops making comparisons, so witness
is left set to the last value checked.
Upvotes: 2
Reputation: 39354
You have to isolate each expression so you can test it later:
my = ['A','B','C']
S = 'S' in my
T = 'T' in my
C = 'C' in my
if S or T or C:
# Now examine S, T and C separately
print('yes')
Upvotes: 0