There are a couple of ways to index through a list in a python loop.
- Using a
while
loop
arr = [i*2 for i in range(1001)]
i = 0
while i < len(arr):
print(arr[i])
i += 1
- Using
range
:
arr = [i*2 for i in range(1001)]
for i in range(len(arr)):
print(arr[i])
- 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)
statement | execution time |
---|---|
with_while_loop | 3.7974138950230554 |
with_range | 3.4823228780878708 |
with_enumerate | 3.410849596024491 |
In reality With_enumerate
wins over with_range
and with_while_loop
.
In theory, all of them run in O(n)
linear time.