Skip to content

Instantly share code, notes, and snippets.

@mekicha
Last active October 1, 2018 14:48
Show Gist options
  • Save mekicha/543644b11f4231b53848c95e71170b45 to your computer and use it in GitHub Desktop.
Save mekicha/543644b11f4231b53848c95e71170b45 to your computer and use it in GitHub Desktop.
Profiling list indexing in a python loop using the timeit module

There are a couple of ways to index through a list in a python loop.

  1. Using a while loop
arr = [i*2 for i in range(1001)]
i = 0
while i < len(arr):
  print(arr[i])
  i += 1
  1. Using range:
arr = [i*2 for i in range(1001)]
for i in range(len(arr)):
  print(arr[i])
  1. Using enumerate:
arr = [i*2 for i in range(1001)]
for _, elem in enumerate(arr):
  print(elem)

But which one of the above is faster, you ask? We can use the built-in timeit module to find out. By default, the timeit function will run the code 1 million times and return the total time it took to run the test. I changed the number to 1000 in this case.

>>> with_while_loop = """\
arr = [i*2 for i in range(1001)]
i = 0
while i < len(arr):
  print(arr[i])
  i += 1
"""
>>> with_range = """\
arr = [i*2 for i in range(1001)]
for i in range(len(arr)):
  print(arr[i])
"""
>>> with_enumerate = """\
arr = [i*2 for i in range(1001)]
for _, elem in enumerate(arr):
  print(elem)
"""
>>> import timeit
>>> timeit.timeit(stmt=with_while_loop, number=1000)
>>> timeit.timeit(stmt=with_range, number=1000)
>>> timeit.timeit(stmt=with_enumerate, number=1000)

Results

statement execution time
with_while_loop 3.7974138950230554
with_range 3.4823228780878708
with_enumerate 3.410849596024491

Conclusion

In reality With_enumerate wins over with_range and with_while_loop. In theory, all of them run in O(n) linear time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment