Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare execution time of different lists in python.
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)
@mathisgauthey
Copy link
Author

Results : [61.77123859999983, 4.757899599999746, 7.002218200000243]

  • len(data) method : 61.77 s
  • implicit method : 4.75 s
  • implicit method with index number : 7 s

@mathisgauthey
Copy link
Author

Defining len(data) beforehand would prevent calculation to take this long and would takes about as much time as with the implicit method.

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