def setup():
global a_list
a_list = [" raz sada ra r era kldfa d dh dsfh fhds h aergl jlk "]*500
def slice_comprehension():
global a_list
a_list[:] = (s.strip() for s in a_list)
def noslice_comprehension():
global a_list
a_list = [s.strip() for s in a_list]
def slice_map():
global a_list
a_list[:] = map(str.strip, a_list)
def noslice_map():
global a_list
a_list = map(str.strip, a_list)
def iter_enumerate():
global a_list
for i,x in enumerate(a_list):
a_list[i] = x.strip()
def iter_range():
global a_list
for i in range(len(a_list)):
a_list[i] = a_list[i].strip()
def iter_manual():
global a_list
i=0
for x in a_list:
a_list[i] = x.strip()
i+=1
import timeit
n=1000
funcs = slice_comprehension, noslice_comprehension, slice_map, noslice_map, iter_enumerate, iter_range, iter_manual
values = [(f.func_name, timeit.timeit(f, number=n, setup=setup)) for f in funcs]
for i in sorted(values, key=lambda x: x[1]):
print "{:25}: {}".format(*i)
CgpkZWYgc2V0dXAoKToKCWdsb2JhbCBhX2xpc3QKCWFfbGlzdCA9IFsiIHJheiBzYWRhIHJhIHIgZXJhIGtsZGZhIGQgZGggZHNmaCBmaGRzIGggYWVyZ2wgamxrICAgICAiXSo1MDAKCmRlZiBzbGljZV9jb21wcmVoZW5zaW9uKCk6CglnbG9iYWwgYV9saXN0CglhX2xpc3RbOl0gPSAocy5zdHJpcCgpIGZvciBzIGluIGFfbGlzdCkKCmRlZiBub3NsaWNlX2NvbXByZWhlbnNpb24oKToKCWdsb2JhbCBhX2xpc3QKCWFfbGlzdCA9IFtzLnN0cmlwKCkgZm9yIHMgaW4gYV9saXN0XQoKZGVmIHNsaWNlX21hcCgpOgoJZ2xvYmFsIGFfbGlzdAoJYV9saXN0WzpdID0gbWFwKHN0ci5zdHJpcCwgYV9saXN0KQoKZGVmIG5vc2xpY2VfbWFwKCk6CglnbG9iYWwgYV9saXN0CglhX2xpc3QgPSBtYXAoc3RyLnN0cmlwLCBhX2xpc3QpCgpkZWYgaXRlcl9lbnVtZXJhdGUoKToKCWdsb2JhbCBhX2xpc3QKCWZvciBpL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