Python range() Function
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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:

  • 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.

[0, 1, 2, 3, 4, 5, 6, 7]

Using range() with Two Arguments

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

[4, 5, 6, 7, 8]

Using range() with Three Arguments

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

[2, 5, 8, 11, 14]

Using range() in Loops

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

Count: 0 Count: 1 Count: 2 Count: 3 Count: 4

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.

[0, 1, 2] [2, 3, 4, 5, 6] [1, 5, 9]

Indexing and Slicing Ranges

Ranges behave like other sequences and support indexing and slicing.

4 [1, 2, 3, 4, 5]

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.

True False

Finding the Length of a Range

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

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