Saturday, February 9, 2019
if 'a' or 'b' in L, where L is a list (Python)
Answer
Answer
I am having trouble with the following logic:
Lets say I have a list L = ['a', 'b', 'c']
Both items are in the list...
if ('a' or 'b') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints It's there!
Only the first item is in the list...
if ('a' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints It's there!
Neither item in the list...
if ('e' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints No sorry
Here's the confusing one Only the second item in the list...
if ('e' or 'a') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints No sorry
I do not understand why this is not registering as a true statement. How does this generalize to an or statement with n conditionals?
Forehead-slapping easy answer in 3,2,1...
Answer
Let's break down the expression:
('e' or 'a') will first check if 'e' is True. If it is, the expression will return 'e'. If not, it will return 'a'.
Since all non-empty strings returns True, this expression will always return 'e'. This means that if ('e' or 'a') in L: can be translated to if 'e' in L, which in this case is False.
A more generic way to check if a list contains at least one value of a set of values, is to use the any function coupled with a generator expression.
if any(c in L for c in ('a', 'e')):
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
When the left part is an object instance, you use -> . Otherwise, you use :: . This means that -> is mostly used to access instance m...
-
i've started to create my website, but now i have few doubts. I've searched, that MySqli object oriented is good to use beca...
-
I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of docume...
No comments:
Post a Comment