Javatpoint Logo
Javatpoint Logo

Python range() Function

Python, one of the most famous programming languages, offers a scope of inherent capabilities that improve on different undertakings. The range() function stands out as a versatile instrument for iteration and sequence creation. We will look the syntax, parameters, and practical applications of the range() function in this article.

Python range() function returns an immutable sequence of numbers starting from 0, increments by 1 and ends at a specified number.

Signature

Parameters

There are three options for the range() function: start, stop, and step. A brief description of each parameter follows:

start (optional): Indicates the beginning stage of the succession. In the event that did not give, it defaults to 0.

stop (required): Characterizes the endpoint of the grouping. Since it is unique, the sequence will end just before it reaches this value.

step: specifies the increment between the sequence's values. In the event that not determined, it defaults to 1.

Return

It returns an immutable sequence of numbers starting from 0, increments by 1, and ends at a specified number.

Python range() Function Example 1

The below example shows the working of range().

Output:

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

Explanation:

Note: We have returned a generator-like object that only prints the output on demand in the preceding example after converting the range to a Python list.

A reach object returned by the reach constructor can likewise be gotten to by its record. Both positive and negative indices can be supported by it.

Python range() Function Example 2

The below example creates a list of number between the given numbers using range() function.

Output:

 
[5, 9]

Python range() Function Example 3

Output:

 
1
3
5
7
9

The step parameter is set to 2 in this example. As a result, odd numbers between 1 and 10 are produced when the previous value is increased by two.

Utilizing the range() Method:

The range() function is used a lot in different programming situations. We should investigate a couple of reasonable applications to outline its utility.

Iterating over a sequence:

When it comes to iterating over a particular range of values, the range() function is frequently combined with loops, such as the for loop. We can easily control the number of iterations by using range() to specify the desired range.

Output:

 
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6

Generating a List of Numbers:

To produce a list of numbers that fall within a predetermined range, the range() function can be combined with other functions like list().

Output:

 
[1, 2, 3, 4, 5]






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA