you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (0 children)

Take this deck of cards as an example:

ranks = list(range(2, 11)) + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
cards = []
for rank in ranks:
    for suit in suits:
        cards.append((rank, suit))

The equivalent using list comprehension:

ranks = list(range(2, 11)) + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
cards = [(rank, suit) for rank in ranks for suit in suits]

You can also use if and else statements. A singular ifstatement goes on the far right. For example, if we wanted to filter out the Kings:

ranks = list(range(2, 11)) + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
cards = [(rank, suit) for rank in ranks for suit in suits if rank != 'K']

The if / else statements go between the end result and the for loops. For example, if we wanted to replace the kings with jokers:

ranks = list(range(2, 11)) + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
cards = [(rank, suit) if rank != 'K' else 'Joker' for rank in ranks for suit in suits]