I have a list called bag. I want to be able to check if only a particular item is in it.
bag = ["drink"]
if only "drink" in bag:
print 'There is only a drink in the bag'
else:
print 'There is something else other than a drink in the bag'
Of course, where I put 'only' in the code there, it is wrong. Is there any simple replacement of that? I have tried a few similar words.
Use the builtin all()
function.
if bag and all(elem == "drink" for elem in bag):
print("Only 'drink' is in the bag")
The all()
function is as follows:
def all(iterable):
for element in iterable:
if not element:
return False
return True
For this reason, an empty list will return True. Since there are no elements, it will skip the loop entirely and return True. Because this is the case, you must add an explicit and len(bag)
or and bag
to ensure that the bag is not empty (()
and []
are false-like).
Also, you could use a set
.
if set(bag) == {['drink']}:
print("Only 'drink' is in the bag")
Or, similarly:
if len(set(bag)) == 1 and 'drink' in bag:
print("Only 'drink' is in the bag")
All of these will work with 0 or more elements in the list.
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