1

Which is faster and why? Is there a noticeable difference?

""" my_list=[1,2,3...N] """

for i in my_list:
    do something

or

for i in range(1,N):
    do something

It seems to me that in the second case the range function would be called N times which might be slower but I don't know how the in operator really works.

3
  • 7
    The range function does not get called N times. If you are using Python 3.x the second method is a bit faster and more memory efficient since range does not construct the whole list in advance. For Python 2.x you can use xrange for the same effect. Commented May 17, 2016 at 7:16
  • Oh I just meant which is faster in python 3: the first method or the second method? Commented May 17, 2016 at 7:25
  • @Jérôme In Python 3 the second method is faster. To make it faster and use less memory in Python 2, you can replace range with xrange. Commented May 17, 2016 at 9:31

1 Answer 1

1
>>> t = timeit.Timer("""for i in range(3):
...     pass""")
>>> t.timeit(1)
2.199320988438558e-06

as apposed to:

>>> t = timeit.Timer("""list_a=[0,1,2]
... for i in list_a:
...     pass""")
>>> t.timeit(1)
4.398641522129765e-06

You can see the time differences between these operations. Besides, you should be aware that in python 2 it is more advisable using xrange instead of range if you don't need all these values at the same time (like simple iteration), since it generates a value at each iteration, which could save lots of memory and sometimes even CPU (in more complicated cases).

for more information: https://wiki.python.org/moin/Generators

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

3 Comments

print is not a good choice for performance testing, as I/O operations are heavy and may falsify statistics
Thank you. What operations would you suggest for good statistical testing?
You can just use pass :)

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.