Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list ONLY contains a certain item

Tags:

python

list

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.

like image 910
reemer9997 Avatar asked Dec 10 '22 17:12

reemer9997


1 Answers

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.

like image 145
Goodies Avatar answered Dec 13 '22 07:12

Goodies