I have two lists of strings which are:
Deck13Sample = [
'Two', 'Three', 'Four', 'Five', 'Six', 'Seven',
'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'
]
CardTypes = [' of Hearts', ' of Spades', ' of Diamonds', ' of Clubs']
I want to multiply the lists, to get a complete deck which would look like
Deck52Sample = ['Two of Hearts', 'Three of Hearts', 'Four of Hearts', ...]
Since Python can not cross-multiply strings built-in, I am totally clueless of what I should do now.
Three options in vanilla Python that come to mind. For all these options, you really don't need to prepend ' of '
to the suit name. I will work with the implication that CardTypes = ['Hearts', 'Spades', 'Diamonds', 'Clubs']
.
Use a nested for
loop. After all, that's what a cross product is:
deck = []
for rank in Deck13Sample:
for suit in CardTypes:
deck.append(f'{rank} of {suit}')
The same thing can be expressed much more concisely as a list comprehension. This is the option I would recommend:
deck = [f'{rank} of {suit}' for rank in Deck13Sample for suit in CardTypes]
Notice that the order of the loops is the same as in #1.
Finally, if you want to use a fancy library import (but one that comes with Python), you can use itertools.product
, which is basically an indefinitely nested set of for
loops, and therefore overkill for this problem:
deck = [f'{rank} of {suit}' for rank, suit in itertools.product(Deck13Sample, CardTypes)]
For reference, the numbers are called "rank" and the symbols are called "suit" on a deck of cards.