Map vs For Loop




Pay Notebook Creator: Elaine Chan0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0
In [2]:
#crosscompute

Map vs For Loop

First, a simple for loop:

In [3]:
items = [1, 2, 3, 4, 5]

squared = []
for x in items:
    squared.append(x ** 2)

% timeit squared
29.4 ns ± 1.55 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [5]:
def sqr(x): return x ** 2
%timeit list(map(sqr, items))
2.91 µs ± 222 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [6]:
%timeit list(map((lambda x: x **2), items))
2.66 µs ± 54.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [7]:
def square():
    items = [1, 2, 3, 4, 5]
    squared = []
    for x in items:
        squared.append(x ** 2)

%timeit square()
2.33 µs ± 46 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
None
In [8]:
def sqr(x):
    return x ** 2

def square_map():
    return list(map(sqr, items))

%timeit square_map()
2.71 µs ± 122 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [9]:
def square_lambda():
    return list(map((lambda x: x **2), items))

%timeit square_lambda()
3.02 µs ± 149 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [18]:
import timeit
In [19]:
timeit.timeit(square) # for loop
Out[19]:
2.377551643992774
In [20]:
timeit.timeit(square_map) # map
Out[20]:
2.5558717439998873
In [21]:
timeit.timeit(square_lambda) # map with lambda
Out[21]:
2.781608500983566
In [ ]: