Search code examples
pythonlistnumpycross-product

How can I do cross multiplication with strings in Python?


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.


Solution

  • 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'].

    1. 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}')
      
    2. 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.

    3. 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.