This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
python3:list_comprehensions [2019/05/07 13:36] jguerin Added syntax example based on for loops. |
python3:list_comprehensions [2019/05/07 16:19] (current) jguerin Moved the multiple loop example, switched x*2 to abs(x) in list example. |
||
---|---|---|---|
Line 15: | Line 15: | ||
</ | </ | ||
- | The same could be achieved in the following list comprehension: | + | The same could be achieved in the following list comprehension((Note that the list comprehension can also be constructed by considering the set-builder construction for the same example:\\ {// |
<code python> | <code python> | ||
- | >>> | + | >>> |
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] | ||
</ | </ | ||
- | The following defines the set of all squares, // | ||
+ | ===== Example Functionality ===== | ||
+ | |||
+ | ==== Multiple Loops ==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | [(0, 0), (0, 1), (0, 4), (1, 0), (1, 1), (1, 4), (4, 0), (4, 1), (4, 4)] | ||
+ | </ | ||
+ | |||
+ | ====Conditionals==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | [(1,3), (1,4), (2,3), (2,1), (2,4), (3,1), (3,4)] | ||
+ | </ | ||
+ | |||
+ | ====Repetitions==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] | ||
+ | </ | ||
+ | |||
+ | ====Processing non-range() iterables==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | >>> | ||
+ | [4, 2, 0, 2, 4] | ||
+ | </ | ||
+ | |||
+ | |||
+ | ====Creating a double list==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | >>> | ||
+ | [[0, 1, 2], [3, 4, 5], [6, 7, 8]] | ||
+ | </ | ||
+ | |||
+ | ====Flattening a double list==== | ||
+ | <code python> | ||
+ | >>> | ||
+ | >>> | ||
+ | [1, 2, 3, 4, 5, 6, 7, 8, 9] | ||
+ | </ | ||
+ | |||
+ | ==== Benchmarks ==== | ||
+ | List comprehensions are typically faster than their loop-based counterparts, | ||
+ | |||
+ | <file python square_comprehension.py> | ||
+ | n = int(10000) | ||
+ | squares = [([(x**2, y**2) for x in range(n) for y in range(n)])] | ||
+ | </ | ||
+ | |||
+ | <file python square_loop.py> | ||
+ | n = int(argv[1]) | ||
+ | |||
+ | squares = [] | ||
+ | |||
+ | for i in range(n): | ||
+ | for j in range(n): | ||
+ | squares.append((i**2, | ||
+ | </ | ||
+ | |||
+ | ^ %%n%% ^ square_comprehension.py((Python 3.5.2)) | ||
+ | ^ 500 | .1864s | ||
+ | ^ 1000 | .7104s | ||
+ | ^ 1500 | 1.572s | ||
+ | ^ 2000 | 2.7992 | ||
+ | |||
+ | Note that both of the above examples require storage of (potentially) millions of tuples. Many problems will not necessarily require //storage// of this many values in memory, but instead iterating over them. In such an instances iteration using for loops or [[python3: |