Python | range() function

Python | range() function

The range() function in Python is used to generate a sequence of numbers. It can take atleast one (stop) and atmost 3 arguments: start, stop, and step.

  • The start argument is the first number in the sequence and is optional, if not provided it defaults to 0.
  • The stop argument is the last number in the sequence (not included) and is required.
  • The step argument is the difference between each number in the sequence and is optional, if not provided it defaults to 1.

The range() function returns a range object, which is an iterable sequence of numbers. It can be used in a for loop or converted to a list using the list() function.

Here are some examples of how to use the range() function:

Generating a sequence of numbers from 0 to 9:

for i in range(10):
    print(i)

This will output:

0
1
2
3
4
5
6
7
8
9

In the above example 0 (default value) will act as start argument, 10 will act as a stop argument and 1 (default value) will act as step argument of range() function.
Generating a sequence of numbers from 5 to 9:

for i in range(5, 9):
    print(i)

This will output:

5
6
7
8
9

In the above example 5 will act as start argument, 9 will act as a stop argument and 1 (default value) will act as step argument of range() function.
Generating a sequence of even numbers from 0 to 8:

for i in range(0, 9, 2):
    print(i)

This will output:

0
2
4
6
8

In the above example 0 will act as start argument, 9 will act as a stop argument and 2 will act as step argument of range() function.
Converting a range object to a list:

nums = list(range(5))
print(nums)

This will output:

[0, 1, 2, 3, 4]

It’s important to note that python 3.x range() function returns an iterator, which is different than python 2.x where it returns a list.

Leave a Reply

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

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds