Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Random insertion of elements K times
When it is required to randomly insert elements K times, the random package provides methods like randint() and choice() to select random positions and elements for insertion.
Example
Below is a demonstration of the same −
import random
my_list = [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90]
print("The list is : ")
print(my_list)
print("The list after sorting is : ")
my_list.sort()
print(my_list)
to_add_list = ["Python", "Object", "oriented", "language", "cool"]
K = 3
print("The value of K is")
print(K)
for element in range(K):
index = random.randint(0, len(my_list))
my_list = my_list[:index] + [random.choice(to_add_list)] + my_list[index:]
print("The resultant list is :")
print(my_list)
The output of the above code is −
The list is : [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90] The list after sorting is : [0, 3, 8, 9, 11, 12, 21, 34, 41, 56, 90] The value of K is 3 The resultant list is : [0, 3, 8, 9, 11, 12, 'Python', 21, 34, 41, 56, 90, 'Object', 'oriented']
How It Works
The algorithm performs the following steps −
Import the random module to access random number generation functions.
Define a list of integers and sort it using the
sort()method for better visualization.Create a list of elements to be randomly inserted into the original list.
Use
random.randint(0, len(my_list))to generate a random index position.Use
random.choice(to_add_list)to select a random element from the insertion list.Insert the selected element at the random position using list slicing and concatenation.
Repeat this process K times to insert K random elements.
Alternative Approach Using insert()
You can also use the insert() method for a more direct approach −
import random
numbers = [10, 20, 30, 40, 50]
elements_to_add = ["A", "B", "C", "D"]
K = 2
print("Original list:", numbers)
for i in range(K):
random_index = random.randint(0, len(numbers))
random_element = random.choice(elements_to_add)
numbers.insert(random_index, random_element)
print("List after", K, "random insertions:", numbers)
Original list: [10, 20, 30, 40, 50] List after 2 random insertions: [10, 'C', 20, 30, 'A', 40, 50]
Conclusion
Random insertion uses random.randint() to generate random positions and random.choice() to select random elements. The insert() method provides a cleaner approach than list slicing for single element insertions.
