Reputation: 341
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.
Upvotes: 5
Views: 20552
Reputation: 4681
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.
Upvotes: 15
Reputation: 6736
You could directly check for equality with a list that only contains this item:
if bag == ["drink"]:
print 'There is only a drink in the bag'
else:
print 'There is something else other than a drink in the bag'
Alternatively if you want to check whether the lists contains any number greater than zero of the same item "drink"
, you can count them and compare with the list length:
if bag.count("drink") == len(bag) > 0:
print 'There are only drinks in the bag'
else:
print 'There is something else other than a drink in the bag'
Upvotes: 1
Reputation: 21243
You can check length of list
if len(bag) == 1 and "drink" in bag:
#do your operation.
Upvotes: 0