Python range() Function

This article goes through the uses of the Python range function and is complete with several examples.

The Python range function is used to create a sequence of numbers from a given start point to a given end point, with a specified increment. The sequence of numbers generated by the range() function are often used in loops, especially the for loop.

Syntax

range(start, end, increment)

The range function takes three parameters.

  • start: The starting value from where the range of values will begin. Included in the range of values. Default value is 0.
  • end: The ending value up til which the range of values will go. Not included in the range of values. If only one parameter is given, it is assumed to be the end value.
  • increment: The increment by which the numbers will be generated. Default is 1. This is the third parameter.

Keep in mind that the range function has an exclusive nature, which means that the last number in the sequence is not included. If the range function parameters are range(0,5), then the number “5” will not be included. See the examples below for further clarification.


Example 1:

for x in range(5):
    print(x)
0
1
2
3
4

The range function returns a range object, hence to get it to display in a readable format, we either iterate it using a loop or use the list function.

Example 2:

>>> list(range(5))
[0, 1, 2, 3, 4]

>>> list(range(10,20,2))
[10, 12, 14, 16, 18]

Decrementing the range function

By changing the third parameter to a negative number, we can decrement the sequence of numbers. Remember to assign the starting and end points accordingly.

Remember to mention all three parameters when adding this third parameter, else python will get confused! If you write, range(5, -1), it will think -1 is the second parameter, instead of the third.

for x in range(5, 0, -1):
    print(x)
5
4
3
2
1

This marks the end of the Python range Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.

Here’s a link back to the main Python Built-in Functions page.