简体   繁体   中英

How to return boolean with list.index?

I would like to know how to return a boolean with list.index() and if it possible. I had tried:

def random():
    gobal cases_occupées
    cases_occupées=[]
    case = randint(0,99)
    if cases_occupées.index(case) == False:
        return case
    else
        random()

But with that code that return an exception ValueError if, so I tried to do something else:

def random():
global cases_occupées
case=randint(0,99)
while True:
    try:
        cases_occupées.index(case)
        break
    except ValueError:
        cases_occupées.append(case)
        return case
random()

But now I have an exception TypeError, I'm sure there is a way with "cases_occupées.index(case) == False" but I don'y find how to do it.

Thanks in advance for your help and sorry for my bad english !

To check if an item is in a list like you're trying to do, use the in operator:

def random():
    global cases_occupées
    cases_occupées=[]
    if case not in cases_occupées:
        return case
    else:
        random()

list.index is used to find where an item is located inside a list, and as you've noticed, it throws an exception if the item isn't in the list.

From the Python documentation:

The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s , and false otherwise. x not in s returns the negation of x in s .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM