Wednesday 12 December 2018

if 'a' or 'b' in L, where L is a list (Python)





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')):

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...