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...
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() .
We can use the append() method, the extend() method, or the * operator to repeat elements of a list in 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.
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')):
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With