Python range() Function

Python range() Function

Kishore V


Python range() Function

The built-in range() function generates an immutable sequence of numbers. It is most commonly used in loops when you need to repeat an action a specific number of times.

The object returned by range() has its own data type called range.

Immutable means the sequence cannot be changed after it is created.

Creating a Range

The general syntax of the range() function is:

range(start, stop, step)

    • start → starting value (inclusive, optional)

    • stop → ending value (exclusive, required)

    • step → difference between values (optional, default is 1)

Using range() with One Argument

When only one argument is provided, it represents the stop value.

The sequence automatically starts from 0.

Output:

[0, 1, 2, 3, 4, 5, 6, 7]
Try it Yourself

Using range() with Two Arguments

With two arguments, the first is the start, and the second is the stop.

Output:

[4, 5, 6, 7, 8]
Try it Yourself

Using range() with Three Arguments

The third argument defines the step size, which controls how much each value increases (or decreases).

Output:

[2, 5, 8, 11, 14]
Try it Yourself

Using range() in Loops

The range() function is widely used with for loops.

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Try it Yourself

Converting a Range to a List

A range object does not directly display all its values.

To see the full sequence, convert it into a list.

Output:

[0, 1, 2]
[2, 3, 4, 5, 6]
[1, 5, 9]
Try it Yourself

Indexing and Slicing Ranges

Ranges behave like other sequences and support indexing and slicing.

Output:

4
[1, 2, 3, 4, 5]
Try it Yourself

Note:

    • Indexing returns a single value

    • Slicing returns a new range object

Checking Membership with in

You can check whether a value exists in a range using the in keyword.

Output:

True
False
Try it Yourself

Finding the Length of a Range

The len() function returns how many numbers exist in a range.

Output:

7
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !