Skip to content

Instantly share code, notes, and snippets.

@AlexanderNenninger
Last active February 13, 2022 21:04
Show Gist options
  • Save AlexanderNenninger/714bc38c94d0d830265147a066f8ae38 to your computer and use it in GitHub Desktop.
Save AlexanderNenninger/714bc38c94d0d830265147a066f8ae38 to your computer and use it in GitHub Desktop.
Compare speed of different ways of constructing a list.
stmt_index = 'ls = [0]*10000\nfor i in range(10000):\n ls[i] = i\n'
stmt_append = 'ls = []\nfor i in range(10000):\n ls.append(i)\n'
stmt_comprehension = '[i for i in range(10000)]'
t_index = timeit(stmt_index, number=10000)
# >>> 3.06s
t_append = timeit(stmt_append, number=10000)
# >>> 4.23s
t_comprehension = timeit(stmt_comprehension, number=10000)
# >>> 2.07s
t_numpy = timeit('ls = arange(10000)', setup='from numpy import arange', number=1000)
# >>> 0.05s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment