- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Random insertion of elements K times
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.
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 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']
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.
- Program to find elements from list which have occurred at least k times in Python
- Python – K middle elements
- Top K Frequent Elements in Python
- Python – Reform K digit elements
- Python - Check if k occurs atleast n times in a list
- Explain insertion of elements in linked list using C language
- Python – Filter rows with Elements as Multiple of K
- Unique element in an array where all elements occur k times except one in C++
- Program to find k where k elements have value at least k in Python
- Python Program for Insertion Sort
- Insertion Sort in Python Program
- Delete elements with frequency atmost K in Python
- Extract tuples having K digit elements in Python
- Python – Next N elements from K value
- Python program to find Non-K distant elements