search by tags

for the user

adventures into the land of the command line

python list comprehensions

i’ve always wanted to learn about how to use list comprehensions in python. so, here we go…

say there are two lists, and i wanna iterate over the two of them, and form a new list from them. in the past i might have used nested for loops.

★ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import time
>>> def doit():
...     t0 = time.time()
...     results = []
...     for i in range(10):
...             for j in range(i):
...                     results.append((i, j))
...     print time.time() - t0
...     return results
...
>>> doit()
3.50475311279e-05
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]

takes x amount of time. but the same can be achieved with a list comprehension.

>>> def go():
...     t0 = time.time()
...     results = [(i, j) for i in range(10) for j in range(i)]
...     print time.time() - t0
...     return results
...
>>> go()
1.8835067749e-05
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]

takes less than x amount of time. noice.