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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)))

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.