Python range()

In this tutorial, we will learn about the Python range() function with the help of examples.

The range() function returns a sequence of numbers.

Example

# create a sequence of numbers from 0 to 5
numbers = range(6)

# converting to a list
numbers_list = list(numbers)

print(numbers_list)
# Output: [2, 3, 4, 5]

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 One 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).

# numbers from 0 to 3 (4 is not included)
numbers = range(4)
print(list(numbers))    # [0, 1, 2, 3]

# if 0 or negative number is passed, we get an empty sequence
numbers = range(-4)
print(list(numbers))    # []

Example 2: range() with Two 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).

# numbers from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers))    # [2, 3, 4]

# numbers from -2 to 3 (4 is not included)
numbers = range(-2, 4)    
print(list(numbers))    # [-2, -1, 0, 1, 2]

# returns an empty sequence of numbers
numbers = range(4, 2) 
print(list(numbers))    # []

Example 3: range() with Three 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.

# numbers from 2 to 10 with increment 3 between numbers
numbers = range(2, 10, 3)
print(list(numbers))    # [2, 5, 8]

# numbers from 4 to -1 with increment of -1
numbers = range(4, -1, -1)    
print(list(numbers))    # [4, 3, 2, 1, 0]

# numbers from 1 to 4 with increment of 1
# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1) 
print(list(numbers))    # [0, 1, 2, 3, 4]

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() is for Loop

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

# iterate the loop 5 times
for i in range(5):
    print(i, 'Hello')
0 Hello
1 Hello
2 Hello
3 Hello
4 Hello

Video: Python range() Function

Did you find this article helpful?