# Python program to randomly create N Lists of K size

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

## Example

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)

## Output

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]]

## Explanation

• 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.

Updated on 16-Sep-2021 08:00:28