Open In App

Python | Create list of numbers with given range

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive). 

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 Creating a list of numbers with a given range in Python

Naive Approach using a loop

A naive method to create a list within a given range is to first create an empty list and append the successor of each integer in every iteration of for loop

Python3




# Python3 Program to Create list
# with integers within given range
 
def createList(r1, r2):
 
 # Testing if range r1 and r2
 # are equal
 if (r1 == r2):
  return r1
 
 else:
 
  # Create empty list
  res = []
 
  # loop to append successors to
  # list until r2 is reached.
  while(r1 < r2+1 ):
    
   res.append(r1)
   r1 += 1
  return res
  
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))


Output:

[-1, 0, 1]

Using List comprehension 

We can also use list comprehension for the purpose. Just iterate ‘item’ in a for loop from r1 to r2 and return all ‘item’ as list. This will be a simple one liner code. 

Python3




# Python3 Program to Create list
# with integers within 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))


Output:

[-1, 0, 1]

Using Python range()

Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list. 

Python3




# Python3 Program to Create list
# with integers within given range
 
def createList(r1, r2):
    return list(range(r1, r2+1))
     
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))


Output:

[-1, 0, 1]

Using itertools:

You can also use the range function in combination with the itertools module’s chain function to create a list of numbers with a given range. This can be done as follows:

Python3




# Python3 Program to Create list
# with integers within given range
import itertools
r1=-5
r2=5
#using the chain function from the itertools module
numbers = list(itertools.chain(range(r1, r2+1)))
print(numbers)
#This code is contributed by Edula Vinay Kumar Reddy


Output

[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]

This will create a list of numbers from r1 to r2 inclusive by chaining the elements in the range together using the chain function from the itertools module.

Using numpy.arange() 

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

Python3




# Python3 Program to Create list
# with integers within 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))


Output:

[-1, 0, 1]

Using numpy to create list of numbers with given range

Here we are creating a list of numbers from a given range with the defined increment.

Python3




import numpy as np
 
def fun(start, end, step):
    num = np.linspace(start, end,(end-start)
                      *int(1/step)+1).tolist()
    return [round(i, 2) for i in num]
     
 
print(fun(1,5,0.5))


Output:

[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

Using Recursion

Another approach to create a list of numbers within a given range is to use recursion. This involves defining a recursive function that takes in the current range and the list to be returned, and then appending the current range to the list and calling the function again with the next range until the end of the range is reached.

Python3




def create_list(r1, r2, lst):
    # Base case: if r1 is equal to r2, return the list
    if r1 == r2+1:
        return lst
    # Otherwise, append r1 to the list and call the function again with r1 + 1
    else:
        lst.append(r1)
        return create_list(r1 + 1, r2, lst)
 
# Test the function
print(create_list(5, 9, []))  # [5, 6, 7, 8, 9]
print(create_list(-1, 1, [])) # [-1, 0, 1]
#This code is contributed by Edula Vinay Kumar Reddy


Output

[5, 6, 7, 8, 9]
[-1, 0, 1]

This approach has a time complexity of O(n) and an auxiliary space of O(n), where n is the number of elements in the list.

Approach 5: Using map() and lambda function

In this approach, we use map() and a lambda function to generate a list of numbers within the given range. map() applies the lambda function to each element in the sequence and returns a map object. We convert the map object to a list and return it.

Algorithm

Use map() and a lambda function to generate a list of numbers within the given range.
Convert the map object to a list and return it.

Python3




def create_list(r1, r2):
    return list(map(lambda x: x, range(r1, r2+1)))
 
 
# Test the function
print(create_list(5, 9))  # [5, 6, 7, 8, 9]
print(create_list(-1, 1))  # [-1, 0, 1]


Output

[5, 6, 7, 8, 9]
[-1, 0, 1]

Time Complexity: O(r2-r1) where r1 and r2 are the given range.
Space Complexity: O(r2-r1) where r1 and r2 are the given range.



Previous Article
Next Article

Similar Reads

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 | 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 | Find missing numbers in a sorted list range
Given a range of sorted list of integers with some integers missing in between, write a Python program to find all the missing integers. Examples: Input : [1, 2, 4, 6, 7, 9, 10] Output : [3, 5, 8] Input : [5, 6, 10, 11, 13] Output : [7, 8, 9, 12] Method #1: List comprehension [GFGTABS] Python # Python3 program to Find missing # integers in list def
5 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python - Test if elements of list are in Min/Max range from other list
Given two lists, the task is to write a Python Program to return true if all elements from second list are in range of min and max values of the first list. Examples: Input : test_list = [5, 6, 3, 7, 8, 10, 9], range_list = [4, 7, 9, 6] Output : True Explanation : Min and max in list 1 are 3 and 10, all elements are in range in other list. Input :
6 min read
Python Program to Find Numbers Divisible by 7 and Multiple of 5 in a Given Range
Given a range of numbers, the task is to write a Python program to find numbers divisible by 7 and multiple of 5. Example: Input:Enter minimum 100 Enter maximum 200 Output: 105 is divisible by 7 and 5. 140 is divisible by 7 and 5. 175 is divisible by 7 and 5. Input:Input:Enter minimum 29 Enter maximum 36 Output: 35 is divisible by 7 and 5.Algorithm
6 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 program to extract characters in given range from a string list
Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 11, 20 Output : sbes
4 min read
Python - Test for all Even elements in the List for the given Range
Given a List of elements, test if all elements are even in a range. Input : test_list = [3, 1, 4, 6, 8, 10, 1, 9], i, j = 2, 5 Output : True Explanation : 4, 6, 8, 10, all are even elements in range. Input : test_list = [3, 1, 4, 6, 87, 10, 1, 9], i, j = 2, 5 Output : False Explanation : All not even in Range. Method #1: Using loop In this, we iter
2 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is updated with 9 from 4th to 8th index. Input : test_
3 min read
three90RightbarBannerImg