Python range()

The range() function returns a sequence of numbers between the give range.

Example

Note: range() returns an immutable sequence of numbers that can be easily converted to lists, tuples, sets etc.


Syntax of range()

The range() function can take a maximum of three arguments:

range(start, stop, step)

The start and step parameters in range() are optional.

Now, let's see how range() works with different number of arguments.


Example 1: range() with Stop Argument

If we pass a single argument to range(), it means we are passing the stop argument.

In this case, range() returns a sequence of numbers starting from 0 up to the number (but not including the number).


Example 2: range() with Start and Stop Arguments

If we pass two arguments to range(), it means we are passing start and stop arguments.

In this case, range() returns a sequence of numbers starting from start (inclusive) up to stop (exclusive).


Example 3: range() with Start, Stop and Step Arguments

If we pass all three arguments,

  • the first argument is start
  • the second argument is stop
  • the third argument is step

The step argument specifies the incrementation between two numbers in the sequence.

Note: The default value of start is 0, and the default value of step is 1. That's why range(0, 5, 1) is equivalent to range(5).


range() in for Loop

The range() function is commonly used in a for loop to iterate the loop a certain number of times. For example,

0 Hello
1 Hello
2 Hello
3 Hello
4 Hello

Video: Python range() Function