Home > front end >  Why is the list contents generated incorrectly in my code?
Why is the list contents generated incorrectly in my code?

Time:07-07

it returns a list of length = 4 // e.g. [8, 'Eight', 7, 'Seven']

I was expecting a list of length = 2// e.g [ (8, 'Eight'), (7, 'Seven') ]

import random
choice_list =[(2, 'Two'), (8, 'Eight'), (3, 'Three'), (7, 'Seven')]
def dealer(cards_list_func):
    initial_cards = []
    for item in range(2):
        initial_cards  = random.choice(cards_list_func)
    return initial_cards

new_list = dealer(choice_list)

CodePudding user response:

The = operator on lists does an operation similar to list.extend().
You want list.append().

So just do:

initial_cards.append(cards_list_func)

CodePudding user response:

The issue is with how you are adding the random choice to the final list of cards. Instead of using =, you want to use .append. Here is a link to a post that might be helpful in understanding the difference between .extend and .append.

Here is an example of what you're looking for:

import random
choice_list =[(2, 'Two'), (8, 'Eight'), (3, 'Three'), (7, 'Seven')]
def dealer(cards_list_func):
    initial_cards = []
    for item in range(2):
        initial_cards.append(random.choice(cards_list_func))
    return initial_cards

new_list = dealer(choice_list)
new_list
> [(2, 'Two'), (3, 'Three')]

CodePudding user response:

random.sample greatly simplifies your code as follows:

import random
choice_list =[(2, 'Two'), (8, 'Eight'), (3, 'Three'), (7, 'Seven')]
def dealer(cards_list_func):
    return random.sample(cards_list_func, min(2, len(cards_list_func)))


new_list = dealer(choice_list)
print(new_list)

Sample output:

[(8, 'Eight'), (3, 'Three')]

Note:

In the original question, random.choice was being used in a loop (two iterations) which could lead to the same selection being made for each of the two choices. That may have been required in which case this is not a precise solution

  • Related