-4

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 !

4
  • 5
    Using enumerate isn't a question of efficiency. It's a question of whether you need the index or not. Commented Jun 30, 2022 at 14:33
  • What does "almost the same result" mean? How different is it? What machine do you have? How many items in the list? Commented Jun 30, 2022 at 14:45
  • Alright, but is it slower because of that index that is not in the second example? Commented Jun 30, 2022 at 14:47
  • Thanks @ThomasWeller, I tried without printing results and I ended up getting the results I wanted with a lot of iterations. Have a great day ! Commented Jun 30, 2022 at 14:53

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.