Create list of numbers with given range in Python


Python can handle any requirement in data manipulation through its wide variety of libraries and methods. When we need to generate all the numbers between a pair of given numbers, we can use python’s inbuilt functions as well as some of the libraries. This article describes such approaches.

Using range

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 ending at a specified number. We can of curse change the starting, ending as well as increment steps to suit our need.

Example

 Live Demo

def getnums(s, e,i):
   return list(range(s, e,i))

# Driver Code
start, end, intval = -3, 6,2
print(getnums(start, end,intval))

Output

Running the above code gives us the following result −

[-3, -1, 1, 3, 5]

Using randrange

The random module can also generate a random number between in a similar way as above. It involves calling the randrange method and supplying the parameters for start, end and interval values.

Example

 Live Demo

import random
def getnums(s, e,i):
   return (random.randrange(s, e,i))

# Driver Code
start, end, intval = 3, 16,2
print(getnums(start, end,intval))

Output

Running the above code gives us the following result −

7

With numpy.arrange

The numpy library also provides a very wide range of functions for these requirements. We use arrange function which will also take the required parameters and give the output as a list.

Example

 Live Demo

import numpy as np
def getnums(s, e,i):
   return (np.arange(s, e,i))

# Driver Code
start, end, intval = 3, 16,2
print(getnums(start, end,intval))

Output

Running the above code gives us the following result −

[ 3 5 7 9 11 13 15]

Updated on: 04-May-2020

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements