Python Range Function Explained with 7 Examples (Complete Guide)

Spread the love

Python Range Function():

The range() function is a built-in function in the Python that returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. The range function must take at least one argument.

Its syntax is as follows:

range(start, stop[, step])

range() takes three arguments. Of the three 2 arguments are optional. I.e., start and step are the optional arguments. A start argument is a starting number of the sequence. i.e., lower limit. By default, it starts with 0 if not specified. A stop argument is an upper limit. i.e.generate numbers up to this number, The range() function doesn’t include this number in the result. The step is a difference between each number in the result. The default value of the step is 1 if not specified.

This function generates the integer numbers between the given start integer to the stop integer, which is generally used to iterate over with for Loop. I accepts an integer and returns a range object, which is nothing but a sequence of integers.

Let’s understand how to use range() function with the help of simple examples.

for i in range(6):

print(i, end=’ ‘)

Output:

0 1 2 3 4 5

In the output, we got integers from 0 to 5. range() function doesn’t include the last number in the result. The most common use of range() function in python is to iterate sequence type (List, string etc ) with for and while loop.

The following points are worth noting about range() function arguments.:

  • range() function only works with the integers i.e., whole numbers.
  • All argument must be integers. You 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.

Let’s see all possible scenarios. Below is the three variant of range() function.

Scenario 1: Using only one argument in range()

for i in range(5):

print(i, end=’ ‘)

Output:

0 1 2 3 4

From the above example, only stop argument is passed to range() function. So by default, it takes start = 0 and step = 1.

Scenario 2: Using two arguments (i.e., start and stop) in range() function

for i in range(5, 10):

print(i, end=’ ‘)

Output:

5 6 7 8 9

From the above example, only two arguments (the start and stop) are passed to the range function. So by default, it took step argument value as 1.

Scenario 3: Using all three arguments in range() function

for i in range(1, 10, 2):

print(i, end=’ ‘)

Output:

1 3 5 7 9

From the above example, all three arguments are specified. i.e. start = 1, stop = 10, step = 2. Note:- In the above program step value is 2 so the difference between each number is 2.

Using the range() function in a for loop:

As you know for loop executes a block of code or statement repeatedly for the fixed number of times. Using for loop we can iterate over a sequence of numbers produced by the range() function.

Let see this with an example. Suppose we have a list of 5 numbers and you want to display each element by doubling it let see how to do it using a for loop and range() function.

for i in range(len(list)):

print( “Element Index[“, i, “]”, “Previous Value “, list[i], “Now “, list[i] * 2)

Output:

Double the list numbers using for loop and range() function

Element Index[ 0 ] Previous Value 3 Now 6

Element Index[ 1 ] Previous Value 6 Now 12

Element Index[ 2 ] Previous Value 9 Now 18

Element Index[ 3 ] Previous Value 12 Now 24

Element Index[ 4 ] Previous Value 15 Now 30

Here using a len(list), we got total elements of a list so we can iterate for loop fixed number of time. In each iteration using a range() function loop gets the index of the current element.

Note: variable i is not getting the value 0, 1, 2, 3, 4 at the same time. i get value sequentially. i.e., in the first iteration i= 0. in the second iteration i become 1 and so on.

The range(n) is of exclusive nature that is why it doesn’t include the last number in the output. i.e., The given end point is never part of the generated result.

For example, range(0, 5) = [0, 1, 2, 3, 4]. i.e. it generates integers from 0 to up to 5 but doesn’t include 5. If you want to include the last number in the output i.e., If you want an inclusive range then pass argument value as stop+step.

Some examples of the inclusive range() function as follows:

Example 1:

start = 1

stop = 5

step = 1

# to get inclusive range change stop as stop+step

stop +=step #now stop is 6

for i in range(start, stop, step):

print(i, end=’ ‘)

Output:

1 2 3 4 5

Example 2:

start = 2

stop = 10

step = 2

# to get inclusive range change stop as stop+step

stop +=step #now stop is 12

for i in range(start, stop, step):

print(i, end=’ ‘)

Output:

2 4 6 8 10

A step is an optional argument in the range function. The step is a difference between each number in the sequence. The default size of a step is 1 if not specified. If the step size is 2, then the difference between each number is 2. We can perform lots of operations by effectively using step argument such as reversing a sequence, printing negative ranges.

We can use negative values in all the arguments of range() function i.e., start, stop and step. Let us see how.

start = -2

stop = -10

tep = -2

print(“Negative number range”)

for number in range(start, stop, step):

print(number, end=’ ‘)

Output:

-2 -4 -6 -8

From the program above,

we set,

start = -2

stop = -10

step = -2

In the 1st iteration of for loop = [-2].

In the 2nd iteration of for loop = [-2,-4] because -2+(-2) == -4 and so on and Last iteration output is [-2,-4,-6,-8]

From the example below, we can learn how to use step argument to display a range of numbers from negative to positive.

for num in range(-2,5,1):

print(num, end=” “)

Output:

-2 -1 0 1 2 3 4

From the example below, we can learn how to use step argument effectively to display numbers from positive to negative.

for num in range(2,-5,-1):

print(num, end=” “)

Output:

2 1 0 -1 -2 -3 -4

Python 3’s range uses the generator. Python 3’s range() will produce value when for loop iteration asked for it. i.e., it The range() doesn’t produce all numbers at once. Python range() function returns an immutable sequence object of integers, so its possible to convert range() output to python list. Use list class to convert range output to list. Let’s understand this with the following example.

print(“Converting python range() to list”)

even_list = list( range(2,10,2))

print(“printing list”, even_list)

Output:

Converting python range() to list

printing list [2, 4, 6, 8]

Python range() function doesn’t support the float numbers. i.e., we cannot use floating-point or non-integer number in any of its argument. we can use only integer numbers. However, we can create a custom range function where we can use float numbers like 0.1 or 1.6 in any of its argument. I have demonstrated this in the below example.

def frange(start, stop=None, step=None):

if stop == None:

stop = start + 0.0

start = 0.0

if step == None:

step = 1.0

while True:

if step > 0 and start >= stop:

break

elif step < 0 and start <= stop:

break

yield (“%g” % start) # return float number

start = start + step

print (“Printing float range”)

list = frange(0.5, 1.0, 0.1)

for num in list:

print (num)

Output:

Printing float range

0.5

0.6

0.7

0.8

0.9

If you want to print sequence of numbers within range by descending order or reverse order then it’s possible, there are two ways to do this.

First is to use a negative or down step value. i.e., set the third argument of a range() to -1. For example, if you want to display a number sequence like [5,4,3,2,1]. Use negative step value. The following code shows the same.

print (“Displaying list of numbers by reverse order using range()”)

for number in range(4,-1,-1):

print (number, end=’ ‘)

Output:

4 3 2 1 0

Alternatively, use the reversed function. The reversed function used to reverse a list of any type. To use the reversed function you need to convert a range output to list first. Let see this with an example.

print (“Printing reversed range”)

reverseed_range = list(reversed(range(0,5)))

print(reverseed_range)

Output:

Printing reversed range

[4, 3, 2, 1, 0]

 

range() function works differently between Python 3 and Python 2. The difference between range() and xrange() functions becomes relevant only when you are using python 2. Because in Python 3 xrange() is renamed to range() and original range() function was deprecated.

Working of range and xrange in Python 2:

Both the range() and xrange() function generates the sequence of numbers. but range() produce a list, and xrange() produces an xrange object i.e. a sequence object of type xrange.

range() generates all numbers at once.

xrange() doesn’t generate all numbers at once. it produces number one by one as for loop moves to the next number.

If you are using python 2.x then yes. as you know in python 2.x range() function loads all the numbers in the main memory before iterating them by for loop this leads to high memory usage and increased execution speed. If you want to write code that will run on both Python 2 and Python 3, you should use range().

Is there a way print range of characters or alphabets? For example like this.

for char in range (‘a’,’z’):

print (char)

Note: Above code is a pseudo-code. Yes, It’s possible using the custom generator. let’s see the example. in the following example, I have demonstrated how to generate ‘a’ to ‘z’ alphabet using the custom range() function. this is inclusive, means it also includes the last character. Here we used a ASCII value range and then convert an ASCII value to a letter using a Chr() function.

Python Program to Generate letters from ‘a’ to ‘z’ using custom range() function

print (“””Generates the characters from `a` to `z`, inclusive.”””)

def character_range(char1, char2):

for char in range(ord(char1), ord(char2)+1):

yield (char)

for letter in character_range(‘a’, ‘z’):

print( chr(letter), end=”, ” )

Output;

Generates the characters from `a` to `z`, inclusive.

a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,

Python range() return value is determined by formula and some value constraints.

Note: If a step is a non-zero, Python range() function checks the value constraint. range() returns an Empty sequence If it doesn’t meet the value constraint.

So you must be thinking why does python range(start, end) not include end ? it has a very simple answer because index always starts with ZERO in python. if you count total numbers between range (5) you will get [0,1,2,3,4] i.e. total count is 5.

range() is constructor returns a range object which is nothing but a sequence of numbers, this range object can also be accessed by its index using slice notation. It supports both positive and negative indices. below example explains the same.

print(“accessing python range object with its index”)

first_number = range(0,10)[0] #printing 0th position number i.e. index ZERO means first number print(“First number in given range is: “, first_number) fifth_number = range(0,10)[4] print(“fifth number in given range is: “, fifth_number)

Output:

accessing python range object with its index

First number in given range is: 0

fifth number in given range is: 4

You can also convert python range() output to list and access this list with its index like this.

sample_list = list( range(1,10) )

print (“second element is “, sample_list[1] )

Output:

second element is 2

 

Range with lists:  

The range values are stores in lists, if you want to print these range values we have to use for function of list array.

Example 1:

a= range(3,15) print(a)

Output:

range(3,15)

 

Example 2:

a= range(3,15) print(list(a))

Output:

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

 

Range with Negative values:

You can print negative values by using range function

Example 3:

a= range(-3,3) print(list(a))

Range with Float values:

This function cannot used for float numbers.

Example 4:

a= range(-3.5,3.0) print('Range values',list(a) )

If you try to use , it will throw an error.

TypeError: ‘float’ object cannot be interpreted as an integer

Example 5:

a= range(3,15) for n in a: print('Range values',n )

Output:

Range values 3
Range values 4
Range values 5
Range values 6
Range values 7
Range values 8
Range values 9
Range values 10
Range values 11
Range values 12
Range values 13
Range values 14

With step number:

Example 6:

a= range(3,15,2) for n in a: print('Range values',n )

Output:

Range values 3
Range values 5
Range values 7
Range values 9
Range values 11
Range values 13

Example 7:

a= range(3,15,5) for n in a: print('Range values',n )

Output:

Range values 3
Range values 8
Range values 13

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *