Search code examples
pythonlistfunctiontuplesreturn

Why is the list contents generated incorrectly in my code?


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)

Solution

  • 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