Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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...

like image 534
Brian Leach Avatar asked Jan 25 '14 00:01

Brian Leach


People also ask

How do you duplicate in Python?

The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list. Python includes a built-in function to support creating a shallow copy of a list: copy() .

How do you copy a list multiple times in Python?

We can use the append() method, the extend() method, or the * operator to repeat elements of a list in python.

How do you copy a string in a list Python?

To make a copy of a string, we can use the built-in slice syntax [:] in Python. Similarly, we can also do it by assigning a string to the new variable. or we can use the str() function to create a string copy.


2 Answers

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')):
like image 198
Steinar Lima Avatar answered Oct 13 '22 19:10

Steinar Lima


Use this instead:

 if 'a' in L or 'b' in L:

If we want to check if all these of this "items" are in the list, all and a generator comprehension is your friend:

items = 'a', 'b', 'c'
if all(i in L for i in items):

Or if any of these items are in the list, use any:

if any(i in L for i in items)
like image 39
aIKid Avatar answered Oct 13 '22 21:10

aIKid