Python | Create a list of numbers with a given range



Examples :

  Input:  r1 = -1, r2 = 1  Output:  [-1, 0 , 1]  Input:  r1 = 5, r2 = 9  Output:  [5, 6, 7, 8, 9] 

Let`s discuss a few approaches to solve this problem.

Approach # 1: The naive approach

The naive method for creating a list in a given range is to create an empty list and add a successor to each integer in each iteration of the for loop.

# Python3 Program for creating a list
# with integers within the given range

 

def createList (r1, r2):

 

# Check r1 and r2 ranges

# equal

if (r1 = = r2):

  return r1

 

else :

 

# Create empty list

res = []

  

  # loop to add I am successors

# list until r2 is reached.

while (r1 & lt; r2 + 1 ):

 

res.append (r1)

r1 + = 1

return res

  
Driver code

r1, r2 = - 1 , 1

print (createList (r1, r2))

Exit :

 [-1, 0, 1] 

Approach # 2 . Understanding < / strong> list

We can also use lists for this purpose. Just iterate over & # 39; item & # 39; in the for loop from r1 to r2 and return all & # 39; item & # 39; as a list. This will be a simple one-line code.

# Python3 List builder
# with integers within the given range

 

def createList (r1, r2):

return [item for item in range (r1, r2 + 1 )]

  
Driver code

r1, r2 = - 1 , 1

print (createList (r1, r2))

Exit :

 [-1, 0, 1] 

Approach # 3: using Python range ()

Python comes with a direct function range () that creates a sequence of numbers from start to end values ​​and prints each element in the sequence. We use range () with r1 and r2, and then convert the sequence to a list.

# Python3 Program for creating a list
# with integers in a given range

 

def createList (r1, r2):

return list ( range (r1, r2 + 1 ))

 
Driver code

r1, r2 = - 1 , 1

print (createList (r1, r2))

Exit:

 [-1, 0, 1] 

Approach # 4 Using numpy.arange()

Python numpy.arange () returns a list with evenly spaced elements. Here we set the spacing to 1 according to our need to get the desired result.

# Python3 List generator
# with integers in the given range

import numpy as np

def createList (r1, r2):

return np.arange (r1, r2 + 1 , 1 )

  
Driver code

r1, r2 = - 1 , 1

print (createList (r1, r2))

Exit:

 [-1 0 1]