- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

When it is required to create N lists randomly that are K in size, a method is defined that shuffles the values and yields the output.

Below is a demonstration of the same

from random import shuffle def gen_random_list(my_val, K): while True: shuffle(my_val) yield my_val[:K] my_list = [12, 45, 76, 32, 45, 88, 99, 0, 1] print("The list is ") print(my_list) K, N = 4, 5 print("The value of K is ") print(K) print("The value of N is ") print(N) my_result = [] for elem in range(0, N): my_result.append(next(gen_random_list(my_list, K))) print("The result is " ) print(my_result)

The list is [12, 45, 76, 32, 45, 88, 99, 0, 1] The value of K is 4 The value of N is 5 The result is [[88, 76, 99, 12], [12, 99, 32, 76], [32, 76, 12, 99], [32, 45, 0, 12], [76, 0, 1, 45]]

The required packages are imported into the environment.

A method named ‘gen_random_list’ is defined that takes a value and ‘K’ as parameter.

It uses the ‘shuffle’ method and ‘yield’ operator along with slicing to give the result.

Outside the method, a list is defined and displayed on the console.

Values for K and N are defined and displayed on the console.

An empty list is defined.

The range between 0 and N is iterated over, and the method is called and the result is appended to the empty list.

This is displayed as output on the console.

- Related Questions & Answers
- Program to split lists into strictly increasing sublists of size greater than k in Python
- Program to find kth lexicographic sequence from 1 to n of size k Python
- Program to merge K-sorted lists in Python
- Python Program to Get K initial powers of N
- Program to find lexicographically smallest subsequence of size k in Python
- Program to find sum of differences between max and min elements from randomly selected k balls from n balls in Python
- Program to find number of increasing subsequences of size k in Python
- Program to find max values of sublists of size k in Python
- Program to rotate a string of size n, n times to left in Python
- Program to reverse linked list by groups of size k in Python
- Merge k Sorted Lists in Python
- Python - Ways to create a dictionary of Lists
- Python program to create a sorted merged list of two unsorted lists
- How to rotate a matrix of size n*n to 90-degree k times using C#?
- All possible permutations of N lists in Python

Advertisements