Saturday, December 12, 2020

Generator of list comprehension in Python

 In [4]: ranks = [str(n) for n in range(2,11)] + list('JQKA')

In [6]: ranks
Out[6]: ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

In [7]: suits = 'spades diamonds clubs hearts'.split()

In [8]: suits
Out[8]: ['spades', 'diamonds', 'clubs', 'hearts']

In [12]: cards = [(yield (rank, suit)) for suit in suits for rank in ranks]

In [13]: c = iter(cards)

In [14]: c
Out[14]: <generator object <listcomp> at 0x7f522c999050>

In [15]: next(c)
Out[15]: ('2', 'spades')

In [16]: next(c)
Out[16]: ('3', 'spades')

In [17]: next(c)
Out[17]: ('4', 'spades')