UzendayoNE
UzendayoNE

Reputation: 161

Checking if index in list exists

I would like to note that I'm using Discord.py and some of it's included libs.

So I'm trying to check if an index in a list exists but I keep getting the ValueError saying that the index does not exist in my list.

Here's my code:

def deal_card(self):
        U = self.usedCards
        randCard = randchoice(list(self.cards))
        if not U: #check if it is empty
            #if it is empty, just add the card to used cards
            U.append(randCard)
        elif U.index(randCard): #check if card is already in the list
            #if it is, pick another one
            randCard = randchoice(list(self.cards))
            U.append(randCard)
        else: #check if card is not in list
            #if it is not, just add it to the used cards
            U.append(randCard)
        return randCard

self.cards is full of card names and self.usedCards is a list of cards alredy picked by randCard. hand is my command and P4 is one of the cards in self.cards

I found some solutions saying that adding a try block will solve the problem but I don't know how to add it in the middle of my if statement.

Thanks in advance!

Upvotes: 1

Views: 395

Answers (4)

user3820991
user3820991

Reputation: 2610

If you would still like to use the .index function for some reason and not follow the above suggestions you could use the try statement as follows:

try:
    c = U.index(randCard)
    randCard = randchoice(list(self.cards))
    U.append(randCard)
except ValueError:
    U.append(randCard)

Upvotes: 1

Wayne Werner
Wayne Werner

Reputation: 51807

This is probably a terrible way to deal your cards, because then you have the cards both in your discard pile and in your deck.

Why not just move the cards around?

import random

cards = ['H{}'.format(val) for val in range(1, 11)]
print(cards)
discard_pile = []

while cards:
    random.shuffle(cards)
    card = cards.pop()
    print('You drew a {}'.format(card))
    discard_pile.append(card)

while discard_pile:
    cards.append(discard_pile.pop())

# or

cards.extend(discard_pile)
discard_pile.clear()

Upvotes: 2

conner.xyz
conner.xyz

Reputation: 7275

You don't need to use the index function:

elif randCard in U:

Upvotes: 1

Nee
Nee

Reputation: 586

list.index() should be used for finding the index of a list's member. To check whether an item is in a list, simply use in:

if not U:
    # do stuff
elif randCard in U:
    # do other stuff

Upvotes: 4

Related Questions