The while and range() vs. for in Python

General rules:

  • Use for instead of while whenever possible.
  • Don’t use range() calls in for loops.
  • There are plenty of exceptions.

The range() is sometimes used to iterate over a sequence indirectly, but the easiest and fastest way to step through a sequence exhaustively is always with a simple for loop.

>>> a = 'developer'
>>> for i in a:
...     print(i, end = ' ')
... 
d e v e l o p e r >>> 

The for loop handles the details of the iteration automatically but if you need to take over the indexing logic then use a while loop.

>>> a = 'developer'
>>> i = 0
>>> while i < len(a):
...     print(a[i], end = ' ')
...     i += 1
... 
d e v e l o p e r >>> 

If you want to generate offsets (not the items at those offsets) you can do manual indexing with for.

>>> a = 'developer'
>>> len(a)
9
>>> list(range(len(a)))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> for i in range(len(a)):
...     print(a[i], end = ' ')
... 
d e v e l o p e r >>>

It is definitely not the best option because it may run slower, and it’s also more work. You’re better off using the simple for.

>>> for i in a:
...     print(i, end = ' ')
... 
d e v e l o p e r >>> 

Leave a Reply