I'm trying to figure out what would be the best way to loop through a list, and I want to convince myself that it is effectively the fastest.
I want to compare these 3 :
for i in range(len(data)):
...
for item in data:
...
for idx,item in enumerate(data):
...
I tried to use timeit to compare these three, but I always get almost the same result. I tried printing things, creating lists, and navigating through a huge list, but I always get the same results. However, I found that there is a performance difference between 1 and 2 (Which is the most efficient way to iterate through a list in python?). I know would like to see what does enumerate do regarding efficiency, but can't find anything on it nor use my results.
Any help would be much appreciated, thanks in advance and have a nice day !
CodePudding user response:
It seems like I had a problem while executing my tests. Printing values seemed to break my results.
I just executed this code :
master='''
data=[2*x for x in range(10000)]
'''
test1='''
for i in range(len(data)):
data[i]=data[i]*5
'''
test2='''
for item in data:
item=item*5
'''
test3='''
for idx,item in enumerate(data):
item=item*5
'''
res=[]
res.append(timeit.timeit(stmt=test1, setup=master, number=10000))
res.append(timeit.timeit(stmt=test2, setup=master, number=10000))
res.append(timeit.timeit(stmt=test3, setup=master, number=10000))
print(res)
And the result is the following : [61.77123859999983, 4.757899599999746, 7.002218200000243]
I once again answered myself in a stack overflow post. I think the pressure I get while posting after many tries ends up exploding my brain and allows me to start fresh. Anyway, hope it'll help, and thanks for your insights!