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 program to randomly create N Lists of K size
When you need to generate multiple random lists of a specific size from a larger dataset, Python's random.shuffle() combined with generator functions provides an efficient solution. This approach creates N lists, each containing K randomly selected elements.
Using Generator Function with Shuffle
Here's how to create a generator that produces random sublists ?
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 original list is:")
print(my_list)
K, N = 4, 5
print(f"Creating {N} lists of size {K}")
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 original list is: [12, 45, 76, 32, 45, 88, 99, 0, 1] Creating 5 lists of size 4 The result is: [[88, 76, 99, 12], [12, 99, 32, 76], [32, 76, 12, 99], [32, 45, 0, 12], [76, 0, 1, 45]]
Alternative Method Using Random Sampling
For cases where you want sampling without replacement, use random.sample() ?
import random
def create_random_lists(data, K, N):
result = []
for _ in range(N):
random_sublist = random.sample(data, K)
result.append(random_sublist)
return result
my_list = [12, 45, 76, 32, 45, 88, 99, 0, 1]
K, N = 4, 5
random_lists = create_random_lists(my_list, K, N)
print("Original list:", my_list)
print(f"Generated {N} random lists of size {K}:")
for i, sublist in enumerate(random_lists, 1):
print(f"List {i}: {sublist}")
Original list: [12, 45, 76, 32, 45, 88, 99, 0, 1] Generated 5 random lists of size 4: List 1: [76, 0, 45, 88] List 2: [32, 99, 45, 12] List 3: [1, 76, 45, 99] List 4: [88, 32, 0, 45] List 5: [76, 1, 12, 99]
How It Works
The generator function approach:
shuffle(my_val) − Randomly reorders the original list in-place
yield my_val[:K] − Returns the first K elements as a slice
while True − Creates an infinite generator for continuous list generation
next() − Gets the next value from the generator
Comparison
| Method | Modifies Original | Allows Duplicates | Best For |
|---|---|---|---|
shuffle() + yield |
Yes | No | Memory efficient, large datasets |
random.sample() |
No | No | Clean code, preserves original |
Conclusion
Use the generator approach with shuffle() for memory-efficient random list generation. For simpler cases where preserving the original list matters, random.sample() provides a cleaner solution without side effects.
