Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Get a sorted list of random integers with unique elements

  • Last Updated : 11 May, 2020

Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end.

Examples:

Input: num = 10, start = 100, end = 200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]

Input: num = 5, start = 1, end = 100
Output: [37, 49, 64, 84, 95]

To generate random numbers in Python, randint() function of random module is used.

Syntax:

randint(start, end)

randint() accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second.

Below is the implementation.




# Python program to create 
# a sorted list of unique random 
# numbers
  
  
import random
  
  
# Function to generate a sorted list  
# of random numbers in a given
# range with unique elements
def createRandomSortedList(num, start = 1, end = 100):
    arr = []
    tmp = random.randint(start, end)
      
    for x in range(num):
          
        while tmp in arr:
            tmp = random.randint(start, end)
              
        arr.append(tmp)
          
    arr.sort()
      
    return arr
   
# Driver's code
print(createRandomSortedList(10, 100, 200))
print(createRandomSortedList(5)))

Output:

[102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
[37, 49, 64, 84, 95]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!