Python Range function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions which you can use in a for loop. You can also use it in many other places where a list of numbers is required.

An example in a for loop looks like below.

The general format of the range function is given below.

With only one argument, range generates a list of integers from zero up to but not including the given number – as can be seen in the above example. If you pass two arguments than the first is taken as a lower bound of the generated numbers.

The following will generate numbers starting from 5 up to 10.

A few additional examples will clear this.

An optional third argument gives a step to the number sequence. If the step option is specified than Python increments each number by the given step. The previous example with the step argument added is given below.

Info: If you had ever programmed in any dialect of Basic than you will be familiar with the STEP command.

Ranges can also be negative and descending.

Note: Python 2.x range creates a physical list, while in 3.x range is an iterable that generates items on demand. Because of this we need to wrap it in a list call to display all its results at once in 3.x.

You can test your Python code using the online code editor.

Leave a Reply

Your email address will not be published. Required fields are marked *