How does the range( ) function work?



How does the range( ) function work?


The range() function’s three different versions give us all kinds of options for generating ranges of numbers.

  1. range(stop) generates a range of numbers from 0 up to the stop point. It does not include the stop number. So writing range(3) gives us [0, 1, 2]. 3 is not included.
  2. range(start, stop) does the same thing, but now we can specify a starting value. The stop is still not included, but start is included. If we have range(0, 3), it produces the same result as above. This is useful when we don’t want to start at 0, though!
  3. range(start, stop, step) works mostly like the above, where start is included, stop is excluded, and now we have another parameter to work with: step. This step tells it by how much to change in value each time. For example, writing range(0, 10, 2) give us [0, 2, 4, 6, 8] because we started at 0, stopped at 10 (not included), and stepped by 2 each time.

FAQ: Learn Python - Lists and Functions - Passing a range into a function