List Comprehension List Comprehension makes it easy to create a List. Comprehension means "include" rather than "understand", and in Japanese it seems to be called a list comprehension.
In [1]: L1 = []
...: for x in range(30):
...: L1.append(x**2)
...:
...: print(L1)
...:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841]
Even if you don't create an empty List and append it, you can apply it in one line as shown below.
In [2]: L2 =[x**2 for x in range(30)]
In [3]: print(L2)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841]
An if statement can follow a for statement.
In [4]: L3 = [x for x in range(30) if x % 2 == 0]
In [5]: print(L3)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
You can also follow the for statement with the for statement.
In [6]: L4 = [(x,y) for x in range(10) for y in range(x,10)]
In [7]: print(L4)
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 6), (6, 7), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 8), (8, 9), (9, 9)]
Generator Comprehension
Generator can be created by changing [] to ()
In [8]: G4 = ((x,y) for x in range(10) for y in range(x,10))
In [9]: G4
Out[9]: <generator object <genexpr> at 0x000000000A395D80>
In [10]: L5 = list(G4)
In [11]: print(L5)
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 6), (6, 7), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 8), (8, 9), (9, 9)]
See here for details.