Skip to content

Instantly share code, notes, and snippets.

@nitely
Last active August 21, 2016 14:20
Show Gist options
  • Select an option

  • Save nitely/05e8c9d0b13e55469b385f56018aaa5d to your computer and use it in GitHub Desktop.

Select an option

Save nitely/05e8c9d0b13e55469b385f56018aaa5d to your computer and use it in GitHub Desktop.
Slow lists, Fast list (python 3)
import timeit
INNER_ITERATIONS = 10000
TIMEIT_ITERATIONS = 5000
def func():
return [x for x in range(INNER_ITERATIONS)]
def func2():
return list(range(INNER_ITERATIONS))
def func3():
res = []
for x in range(INNER_ITERATIONS):
res.append(x)
return res
def func4():
return list(x for x in range(INNER_ITERATIONS))
def func5():
return [*range(INNER_ITERATIONS)]
assert func() == func2() == func3() == func4() == func5()
for f in (func, func2, func3, func4, func5):
print('{}: {}'.format(f.__name__, timeit.timeit(f, number=TIMEIT_ITERATIONS)))
# func: 1.9709388579940423
# func2: 1.1561449829969206
# func3: 4.777506334001373
# func4: 3.2804647559969453
# func5: 1.1617357560025994
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment