Total_PyNoob
Total_PyNoob

Reputation: 13

How to check element as you append element in python list?

New to python with limited prior programming experience, I'm trying to create a card game as a learning vehicle. The first step is to deal cards. I know there are many ways to do this including creating card objects and deal methods. That will come later.

For now, I want to randomly generate suites and numbers, concatenate the values into a string and append the element in a list. As the cards are dealt, the newly generated element will be compared against what's already in the list to see if it's a repeat. If it is, then regenerate the element. I'm having trouble checking the element as I'm adding the element to the list. Everything I found on this topic has been checking the list against a static known value. I want to dynamically check the element against what's already in the list as new elements are added to the list. Below is what I have so far. Any help is much appreciated!


import random

player_count =int(input('Welcome! How many players? '))

for i in range (player_count):

    x = random.randint(1,13)
    y = random.choice(['-Spade','-Heart','-Diamond','-Club'])
    card_set =[str(x) + y]
    if card_set not in card_set:
        card_set.append
        print(card_set)

Upvotes: 1

Views: 150

Answers (2)

Jordan
Jordan

Reputation: 491

You're setting card_set fresh on every pass through the loop.

saved = []
for i in range(10):
    draw = new_draw() # returns a string
    if draw not in saved:
        saved.append(draw)

Upvotes: 3

ApplePie
ApplePie

Reputation: 8942

Instead of setting card_set before the if condition, you should create another variable and assign the new result. If that new result is not in card_set then proceed.

player_count = int(input('Welcome! How many players? '))
for i in range (player_count):
    x = random.randint(1,13)
    y = random.choice(['-Spade','-Heart','-Diamond','-Club'])
    card = str(x) + y
    if card not in card_set:
        #do some stuff

Upvotes: 1

Related Questions