-2

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)
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Will108
  • 3
  • 2
  • Take a look at *random.sample*. With your current use of *random.choice* you could select the same 'card' twice and that may not be what you want – DarkKnight Jul 07 '22 at 07:20

3 Answers3

2

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

So just do:

initial_cards.append(cards_list_func)
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
2

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')]
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
genhernandez
  • 453
  • 1
  • 5
  • 19
1

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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22