Python range function
Contents
The Python range
type generates a sequence of integers by defining the start and end points of a range. It is typically used with a for
loop to iterate over a sequence of numbers.
range()
works differently in Python 2 and 3.
In Python 2, there are two functions that allow you to generate sequences of integers range
and xrange
. These functions are very similar, the main difference being that range
returns a list and xrange
returns an xrange object.
In Python 3, the xrange
function has been removed, and the range
function behaves similarly to Python 2 xrange
. Python 3 range
is not a function, but a type representing an immutable sequence of numbers.
In this article, we’ll cover the basics of the Python 3 range
type.
Python range()
syntax
The range
constructor takes the following form.
|
|
The arguments provided to the range
constructor must be integers. Floating point numbers and other types are not allowed.
range
takes one required argument and two optional arguments. It returns a range object representing the given range, and generates numbers as needed.
Python range(stop)
When only one independent variable is given, range
returns a sequence of numbers, in increments of 1
, from 0
to stop - 1
.
The following range types are available.
|
|
The generated sequence of numbers starts with 0
and ends with 4
(5-1).
|
|
If the argument is 0
or a negative integer range
, the empty sequence is returned.
|
|
We are converting the range
object to a list, because range
performs inert computation on a sequence of integers. The output is an empty list.
|
|
Python range(start, stop)
When supplied with two arguments, range
returns a sequence of numbers from start
to stop - 1
, in increments of 1
.
The following are examples.
|
|
|
|
The stop
parameter must be greater than start
. Otherwise, the sequence is empty.
|
|
|
|
You can use 0
, positive integers and negative integers as parameters.
|
|
|
|
|
|
|
|
Python range(start, stop, step)
Given three independent variables, range
returns a sequence of numbers from start
to stop - 1
, incremented or decremented by step
.
If step
is positive, then range
returns the increasing sequence.
|
|
|
|
When incrementing, the stop
parameter must be greater than start
. Otherwise, the sequence is empty.
If step
is negative, then range
returns a decreasing sequence.
|
|
|
|
When decreasing, the stop
parameter must be smaller than start
. Otherwise, the sequence is empty.
If step
is 0
, a ValueError exception will be thrown.
|
|
Conclusion
The Python range
type lets you generate sequences of integers. It is mainly used in for
loops.