파이썬 컴프리헨션은 시퀀스를 생성하는 문법.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [f'{x} * {y} = {x * y}' for x in range(2, 10) for y in range(2, 10)]
['2 * 2 = 4',
'2 * 3 = 6',
'2 * 4 = 8',
'2 * 5 = 10',
'2 * 6 = 12',
'2 * 7 = 14',
'2 * 8 = 16',
'2 * 9 = 18',
'3 * 2 = 6',
'3 * 3 = 9',
'3 * 4 = 12',
'3 * 5 = 15',
'3 * 6 = 18',
'3 * 7 = 21',
...
'9 * 7 = 63',
'9 * 8 = 72',
'9 * 9 = 81']
>>> [x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8]
>>> [(x, y) for x in 'ABC' for y in [1, 2, 3]]
[('A', 1),
('A', 2),
('A', 3),
('B', 1),
('B', 2),
('B', 3),
('C', 1),
('C', 2),
('C', 3)]
>>> { x for x in range(10) }
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> { str(x): x for x in range(10) }
{'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9}
>>> gen = (x for x in range(10))
>>> type(gen)
generator
>>> gen.__next__()
0
>>> gen.__next__()
1
>>> for e in gen:
print(e)
2
3
4
5
6
7
8
9