HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Making a deck of cards in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cardsmakingdeckpython

Problem

I want to have a deck of cards that looks like this:

['H1', 'H2', 'H3', 'H4', 'H5', 'H6'...]

For that I wrote the following code:

import itertools
    kind = 'HCDS'
    value = ['1','2','3','4','5','6','7','8','9','10','J','Q','K','A']
    temp = list(itertools.product(kind,value))

    deck = []
    for i in range(0, len(temp)): 
        (a,b) = temp[i]
        deck.append(a+b)
    print(deck)


I was wondering if it could be done easier without the use of this temp variable or the for loop.

Solution

You could just use str.join in a list comprehension and create deck directly:

import itertools 
kind = 'HCDS' 
value = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
deck = ["".join(card) for card in itertools.product(kind,value)]


Note that a regular French card set starts at 2, there is no 1.

Code Snippets

import itertools 
kind = 'HCDS' 
value = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
deck = ["".join(card) for card in itertools.product(kind,value)]

Context

StackExchange Code Review Q#148174, answer score: 22

Revisions (0)

No revisions yet.