#crosscompute
First, a simple for loop:
items = [1, 2, 3, 4, 5]
squared = []
for x in items:
squared.append(x ** 2)
% timeit squared
def sqr(x): return x ** 2
%timeit list(map(sqr, items))
%timeit list(map((lambda x: x **2), items))
def square():
items = [1, 2, 3, 4, 5]
squared = []
for x in items:
squared.append(x ** 2)
%timeit square()
def sqr(x):
return x ** 2
def square_map():
return list(map(sqr, items))
%timeit square_map()
def square_lambda():
return list(map((lambda x: x **2), items))
%timeit square_lambda()
import timeit
timeit.timeit(square) # for loop
timeit.timeit(square_map) # map
timeit.timeit(square_lambda) # map with lambda