Constantine32 Constantine32 - 1 month ago 11
Python Question

Python looping range vs looping array

for i in range(-1, 2):
pass


vs

for i in [-1, 0, 1]:
pass


What is best? I assume second option has better readability? Which is faster?

Especifications:


  1. I always use python3

  2. Yeah I noticed the "Which is faster?" questions is dumb in a way. Woudn't manually type a long enough list to notice a difference by hand.


Answer Source

Using range() is technically a bit slower than just typing out the list as the range() function has to create a list and that takes ~0.012 seconds.

Tests:
Using range() took ~0.045 seconds.
Using a list with the same amount of characters took ~0.033 seconds.

I do recommend that you use range() as it is much easier and the small difference of ~0.012 seconds is not worth it.

I hope this helped!