
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
Random Insertion of Elements K Times in Python
When it is required to randomly insert elements K times, the ‘random’ package and methods from the random package along with a simple iteration is used.
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)
Output
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']
Explanation
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
It is sorted using the ‘sort’ method and is displayed on the console again.
The value of K is defined and is displayed on the console.
The value of K is iterated over, and the ‘randint’ from the ‘random’ package is used to generate the elements of the index.
The list indexing and the ‘choice’ method from the ‘random’ package is used to add values to the list using the concatenation operator.
This list is displayed as the output on the console.