The Wayback Machine - https://web.archive.org/web/20241002133335/https://www.geeksforgeeks.org/python-range-function/
Open In App

Python range() function

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops.

Example

In the given example, we are printing the number from 0 to 4.

Python
for i in range(5):
    print(i, end=" ")
print()

Output:

0 1 2 3 4 

Syntax of Python range() function

Syntax: range(start, stop, step)

Parameter :

  • start: [ optional ] start value of the sequence
  • stop: next value after the end value of the sequence
  • step: [ optional ] integer value, denoting the difference between any two numbers in the sequence

Return : Returns an object that represents a sequence of numbers

What is the use of the range function in Python

In simple terms, range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end, as well as how big the difference will be between one number and the next. Python range() function takes can be initialized in 3 ways.

  • range (stop) takes one argument.
  • range (start, stop) takes two arguments.
  • range (start, stop, step) takes three arguments.

Python range (stop)

When the user call range() with one argument, the user will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number that the user has provided as the stop.

Python range (stop)

Python range visualization

Example of Python range (stop)

In this example, we are printing the number from 0 to 5. We are using the range function in which we are passing the stopping of the loop.

Python3
# printing first 6
# whole number
for i in range(6):
    print(i, end=" ")
print()

Output: 

0 1 2 3 4 5 

Python range (start, stop)

When the user call range() with two arguments, the user gets to decide not only where the series of numbers stops but also where it starts, so the user doesn’t have to start at 0 all the time. Users can use range() to generate a series of numbers from X to Y using range(X, Y).

Image

Python range visualization

Example of Python range (start, stop)

In this example, we are printing the number from 5 to 19. We are using the range function in which we are passing the starting and stopping points of the loop.

Python3
# printing a natural
# number from 5 to 20
for i in range(5, 20):
    print(i, end=" ")

Output: 

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Python range (start, stop, step)

When the user call range() with three arguments, the user can choose not only where the series of numbers will start and stop, but also how big the difference will be between one number and the next. If the user doesn’t provide a step, then range() will automatically behave as if the step is 1. In this example, we are printing even numbers between 0 and 10, so we choose our starting point from 0(start = 0) and stop the series at 10(stop = 10). For printing an even number the difference between one number and the next must be 2 (step = 2) after providing a step we get the following output (0, 2, 4, 8). 

Image

Python range visualization

Example of Python range (start, stop, step)

In this example, we are printing the number from 0 to 9 with the jump of 2. We are using the range function in which we are passing the starting and stopping points with the jump of the iterator.

Python3
for i in range(0, 10, 2):
    print(i, end=" ")
print()

Output: 

0 2 4 6 8

Incrementing the Range using a Positive Step 

If a user wants to increment, then the user needs steps to be a positive number.

Python3
# incremented by 4
for i in range(0, 30, 4):
    print(i, end=" ")
print()

Output : 

0 4 8 12 16 20 24 28

Python range() using Negative Step

If a user wants to decrement, then the user needs steps to be a negative number. 

Python3
# incremented by -2
for i in range(25, 2, -2):
    print(i, end=" ")
print()

Output : 

25 23 21 19 17 15 13 11 9 7 5 3 

Python range() with Float Values

Python range() function doesn’t support float numbers. i.e. user cannot use floating-point or non-integer numbers in any of its arguments. Users can use only integer numbers.

Python3
# using a float number
for i in range(3.3):
    print(i)

Output : 

for i in range(3.3):
TypeError: 'float' object cannot be interpreted as an integer

Python range() with More Examples

Concatenation of two range() functions using itertools chain() method

The result from two range() functions can be concatenated by using the chain() method of itertools module. The chain() method is used to print all the values in iterable targets one after another mentioned in its arguments.

Python3
from itertools import chain

# Using chain method
print("Concatenating the result")
res = chain(range(5), range(10, 20, 2))

for i in res:
    print(i, end=" ")

Output : 

Concatenating the result
0 1 2 3 4 10 12 14 16 18

Accessing range() with an Index Value

A sequence of numbers is returned by the range() function as its object that can be accessed by its index value. Both positive and negative indexing is supported by its object.

Python3
ele = range(10)[0]
print("First element:", ele)

ele = range(10)[-1]
print("\nLast element:", ele)

ele = range(10)[4]
print("\nFifth element:", ele)

Output : 

First element: 0
Last element: 9
Fifth element: 4

range() function with List in Python

In this example, we are creating a list and we are printing list elements with the range() in Python.

Python
fruits = ["apple", "banana", "cherry", "date"]

for i in range(len(fruits)):
    print(fruits[i])

Output :

apple
banana
cherry
date

Some Important points to remember about the Python range() function

  • The range() function only works with integers, i.e. whole numbers.
  • All arguments must be integers. Users can not pass a string or float number or any other type in a start, stop, and step argument of a range().
  • All three arguments can be positive or negative.
  • The step value must not be zero. If a step is zero, python raises a ValueError exception.
  • range() is a type in Python.
  • Users can access items in a range() by index, just as users do with a list.

Python range() function – FAQs

What Does the range() Function Do in Python?

The range() function generates a sequence of numbers, which is commonly used for looping a specific number of times in for loops. It produces an immutable sequence of integers from the start (inclusive) to the stop (exclusive) with a specified step.

How to Create a Sequence of Numbers with range()?

You can create a sequence of numbers using range() by specifying the start, stop, and step arguments.

Example:

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

Output:

0
1
2
3
4

In this example, range(5) generates numbers from 0 to 4.

What Are the Parameters of the range() Function?

The range() function has three parameters:

  1. start (optional): The starting value of the sequence. The default is 0.
  2. stop (required): The ending value of the sequence (exclusive).
  3. step (optional): The difference between each number in the sequence. The default is 1.

Syntax:

range(start, stop, step)

How to Use a Negative Step in the range() Function?

You can use a negative step to generate a sequence in reverse order.

Example:

for i in range(10, 0, -2):
print(i)

Output:

10
8
6
4
2

In this example, range(10, 0, -2) generates numbers from 10 to 2, decrementing by 2.

How to Generate a List Using range()?

To generate a list using range(), you can use the list() function to convert the range object into a list.

Example:

numbers = list(range(5))
print(numbers)

Output:

[0, 1, 2, 3, 4]

Another example with all parameters:

numbers = list(range(2, 10, 2))
print(numbers)

Output:

[2, 4, 6, 8]


Previous Article
Next Article

Similar Reads

range() vs xrange() in Python
The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(). Both are implemented in different ways and have
4 min read
Python range() Method
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Syntax : range(start, stop, step)Parameters : start : Element from which sequence const
3 min read
Python | Numbers in a list within a given range
Given a list, print the number of numbers in the given range. Examples: Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4 Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter
6 min read
Python | Count unset bits in a range
Given a non-negative number n and two values l and r. The problem is to count the number of unset bits in the range l to r in the binary representation of n, i.e, to count unset bits from the rightmost lth bit to the rightmost rth bit. Examples: Input : n = 42, l = 2, r = 5 Output : 2 (42)10 = (101010)2 There are '2' unset bits in the range 2 to 5.
2 min read
Python | Count set bits in a range
Given a non-negative number n and two values l and r. The problem is to count the number of set bits in the range l to r in the binary representation of n, i.e, to count set bits from the rightmost lth bit to the rightmost rth bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n. Examples: Input : n = 42, l = 2,
2 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Python | range() does not return an iterator
range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and range we can not
2 min read
range() to a list in Python
Often times we want to create a list containing a continuous value like, in a range of 100-200. Let's discuss how to create a list using the range() function. Will this work ? # Create a list in a range of 10-20 My_list = [range(10, 20, 1)] # Print the list print(My_list) Output : As we can see in the output, the result is not exactly what we were
1 min read
Python | Remove all sublists outside the given range
Given, list of lists and a range, the task is to traverse each sub-list and remove sublists containing elements falling out of given range. Examples: Input : left= 10, right = 17, list = [[0, 1.2, 3.4, 18.1, 10.1], [10.3, 12.4, 15, 17, 16, 11], [100, 10, 9.2, 11, 13, 17.1], ] Output: [[10.3, 12.4, 15, 17, 16, 11]] Input : left= 1, right = 9, list =
3 min read
Python | Find elements within range in numpy
Given numpy array, the task is to find elements within some specific range. Let's discuss some ways to do the task. Method #1: Using np.where() # python code to demonstrate # finding elements in range # in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6]) # printing initial array print("initial_array : ",
2 min read
rangev2 - A new version of Python range class
range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. The range() function is used to generate a sequence of numbers. But the sequence of numbers produced by range is generally either decreasing or increasing linearly which means it is either incremented and decremented by a part
2 min read
Python | Size Range Combinations in list
The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes in range between i and j. Let’s discuss certain ways in which this function can be performed. Method #1 : Using list comprehension + combinations() This task c
4 min read
Python Pytorch range() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.range() returns a 1-D tensor of size [Tex]\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1[/Tex] with values from start to end with step step. Step is t
1 min read
Python Tkinter - SpinBox range Validation
Prerequisites: Python GUI - tkinter, Python Tkinter – Validating Entry Widget Tkinter is a Python GUI (Graphical User Interface) module which is quick and easy to implement and is widely used for creating desktop applications. It provides various basic widgets to build a GUI program. In Tkinter, Spinbox is commonly used widget to select the fixed n
2 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
Python - Iterating through a range of dates
In this article, we will discuss how to iterate DateTime through a range of dates. Using loop and timedelta to Iterate through a range of dates Timedelta is used to get the dates and loop is to iterate the date from the start date to end date Syntax: delta = datetime.timedelta(days=1) Example: Python code to display the dates from 2021 - Feb 1st to
2 min read
Python Plotly: How to set the range of the y axis?
In this article, we will learn how to set the range of the y-axis of a graph using plotly in Python. To install this module type the below command in the terminal: pip install plotly Example 1: Using layout_yaxis_range as a parameter In this example, we have first import the required libraries i.e pandas,numpy and plotly.objs, then we generated som
3 min read
Python Indexerror: list assignment index out of range Solution
In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range. Python Indexerror: list assignment index out of range ExampleIf ‘fruits’ is a list, fruits=[‘Apple’,’ Banan
3 min read
Python List Index Out of Range - How to Fix IndexError
In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we pr
3 min read
How To Fix - UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) in Python
Several errors can arise when an attempt to change from one datatype to another is made. The reason is the inability of some datatype to get casted/converted into others. One of the most common errors during these conversions is Unicode Encode Error which occurs when a text containing a Unicode literal is attempted to be encoded bytes. This article
2 min read
Python Overflowerror: Math Range Error
Python is a powerful and versatile programming language, widely used for various applications. However, developers may encounter errors during the coding process. One such error is the 'OverflowError: Math Range Error.' This article will explore what this error is, discuss three common reasons for encountering it, and provide approaches to resolve
4 min read
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
In this article, we will understand the reason for "1000000000000000 in range(1000000000000001)" so fast in Python 3 with code Implementation. Why is 1000000000000000 in range(1000000000000001) so fast in Python 3?Reason :"1000000000000000 in range(1000000000000001)" is fast in Python 3 because Python's range() function generates a range object tha
2 min read
Alphabet range in Python
When working with strings and characters in Python, you may need to create a sequence of letters, such as the alphabet from 'a' to 'z' or 'A' to 'Z'. Python offers various options for accomplishing this, taking advantage of its rich string handling features. This article will go over numerous ways to construct and manipulate letter ranges in Python
3 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Sqlalchemy Core With Text SQL For Date Range
SQLAlchemy Core is a low-level SQL abstraction layer of SQLAlchemy, a popular Python Object Oriented Mapping(ORM) library. It provides a way to interact with relational databases wing python code, allowing developers to write SQL Queries in a more object-oriented manner. SQLAlchemy is a python library that provides a set of tools for working with d
2 min read
Scala | Create Array with Range
Array is a special kind of collection in Scala. It is a fixed size data structure that stores elements of the same data type. By using range() method to generate an array containing a sequence of increasing integers in a given range. We can use final argument as jump to create the sequence. if we do not use final argument, then jump would be assume
4 min read
Article Tags :
Practice Tags :