
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Sorted List of Unique Random Integers Using Python
Generating random numbers is one of the most popular techniques in programming, statistics, machine learning models, etc. Generating a sorted list of random integers with unique elements is a subdomain of the task. However, computers are deterministic machines, so generating random numbers through our implementation is only sometimes a smart idea. In this article, we will explore how to Get a sorted list of random integers with unique elements using Python.
Utilizing Sample Function Of Random Module
The sampling method generates random samples of k elements from a given population. It takes two required parameters first is the list of the elements, and next is the number of elements that should be present in our sampled list.
Syntax
random.sample(iterable object, k)
The function sample takes two required parameters: the iterable object and the number of elements that should be present in our result. It returns k elements as a list out of the iterable object.
sorted(iterable, key=< value of the key > , reverse = <boolean True or False> )
The function sorts the iterable object. It takes the iterable object as the required parameter. We can also set the keys of the elements using the key parameter. We can also return the reversed form of the sorted iterable object using the reverse parameter.
Example
In the following code, we first imported the random module of Python. Next, we created the generate_sorted_random_integers function, which takes three arguments for the start range, end range, and the number of elements. We used the range method to create a list of the integers in the range, a sample method to take some samples out of it, and a sorted method to sort the array finally.
import random def generate_sorted_random_integers(start_range, end_range, num_elements): random_list = sorted(random.sample(range(start_range, end_range + 1), num_elements)) return random_list start_range = 1 end_range = 100 num_elements = 10 random_list = generate_sorted_random_integers(start_range, end_range, num_elements) print(f"The sorted list of random integers is: {random_list}")
Output
The sorted list of random integers is: [6, 18, 19, 55, 63, 75, 88, 91, 92, 94]
Utilize The Numpy Module
Numpy is a popular library of Python for Numerical calculations. It also offers us the function to create random numbers. We can utilize the sort method to sort the list and the choice method available to sample k elements
Syntax
numpy.choice(<array name>, size=<shape of the output array> , replace= <Boolean True or False>, other parameters....)
Example
In the following example, after importing the Numpy library, we have defined the generate_sorted_random_integers function. The function takes the start, end, and number of elements as the arguments and returns a randomly sorted list. Under the function, we have used the range function to generate a sequence, the choice method to use only the required number of elements from it, and finally sort method to sort the list.
import numpy as np def generate_sorted_random_integers(start_range, end_range, num_elements): random_list = np.sort(np.random.choice(range(start_range, end_range + 1), size=num_elements, replace=False)) return random_list start_range = 10 end_range = 100 num_elements = 10 random_list = generate_sorted_random_integers(start_range, end_range, num_elements) print(f"The sorted list of random integers is: {random_list}")
Output
The sorted list of random integers is: [23 27 61 72 74 79 80 90 96 99]
Use List Comprehension And Sorting
list comprehension is a popular technique among Python developers. The advantage of this method is that one can combine logical statements, iterative expressions, conditional expressions, etc., in a single line and generate elements for the list depending upon it. This helps to write a single comprehension line of code
Example
In the following example, we used list comprehension to create a sorted list of random numbers. We used the random library of Python to create random numbers in the required range and the sorted method to sort the list of random numbers. We called the user-defined function, passed the necessary parameters, and printed the result.
import random def generate_sorted_random_integers(start_range, end_range, num_elements): random_list = sorted([random.randint(start_range, end_range) for _ in range(num_elements)]) return random_list start_range = 10 end_range = 50 num_elements = 10 random_list = generate_sorted_random_integers(start_range, end_range, num_elements) print(f"The sorted list of random integers is: {random_list}")
Output
The sorted list of random integers is: [12, 13, 15, 16, 16, 25, 28, 29, 47, 49]
Use Lambda Function
Lambda functions do not have any name and are intended to behave like a traditional function if the number of lines of code is small. The function can take arguments and return values. However, the function does not have any name. Usually, we use such a function when we need to perform some operations quickly, and we are sure this operation won't be used elsewhere.
Example
In the following code, we have used the lambda function, which takes the start, end, and number of elements as the arguments. The function also uses list comprehension to generate elements of the list. We used the randint method to generate random numbers and the sorted method to sort the list.
import random generate_sorted_random_integers = lambda start_range, end_range, num_elements: sorted([random.randint(start_range, end_range) for _ in range(num_elements)]) start_range = 1 end_range = 100 num_elements = 10 random_list = generate_sorted_random_integers(start_range, end_range, num_elements) print(f"The sorted list of random integers is: {random_list}")
Output
The sorted list of random integers is: [7, 14, 32, 46, 55, 68, 79, 84, 88, 90]
Use Lambda Function
Pandas is a popular data analysis library of Python. It has an in-built function called apply, which we can use to apply some operation to all the list elements. We can use the random library to generate the random numbers and apply the method to sort the elements
Use Pandas Library With Random
Pandas is a popular data analysis library of Python. It has an in-built function called apply, which we can use to apply some operation to all the list elements. We can use the random library to generate the random numbers and apply the method to sort the elements
Syntax
DataFrame.apply(<function to apply to the elements>, axis=<0 for rows and 1 for columns> , raw=<boolean True or False> , result_type=None, other parameters.....)
We can use the apply method on the data frame objects of Pandas. It takes the name of the function as the required parameter. The function is applied to all the elements of the data frame. axis parameter defines whether we need to use the function with the rows or columns. convert_type is a boolean that indicates whether to convert the data type of the resulting Series to the common type inferred from the function's return values
Example
We first imported the Pandas library with aliasing as pd in the following code. Next, we have created a data frame named df using the DataFrame method. We used the apply method to the data frame and used the generate_sorted_random_integers function for all the numbers. The generate_sorted_random_integers function uses the sampling method to sample some random numbers, and the sort method sorts the list numbers.
import pandas as pd import random df = pd.DataFrame({ 'start_range': [1, 1, 1], 'end_range': [100, 100, 100], 'num_elements': [10, 10, 10] }) def generate_sorted_random_integers(row): random_list = random.sample(range(row[0], row[1] + 1), row[2]) random_list.sort() return random_list random_list = df[['start_range', 'end_range', 'num_elements']].apply(generate_sorted_random_integers, axis=1).tolist() print(f"A multidimensional sorted list of random integers with unique elements are as follows: {random_list}")
Output
A multidimensional sorted list of random integers with unique elements are as follows: [[11, 28, 31, 32, 35, 58, 73, 82, 88, 96], [17, 26, 42, 45, 47, 55, 89, 97, 99, 100], [26, 32, 66, 73, 74, 76, 85, 87, 93, 100]]
Conclusion
In this article, we understood how to get a sorted list of random integers with unique elements using Python. The random Module is the most prominent way to generate random numbers since it was designed for this purpose. However, to generate a sorted list, we also need to use some other methods available in Python, like the choice, sample, lambda function, etc.