Python program to randomly create N Lists of K size
Last Updated :
18 May, 2023
Given a List, the task is to write a Python program to randomly generate N lists of size K.
Examples:
Input : test_list = [6, 9, 1, 8, 4, 7], K, N = 3, 4
Output : [[8, 7, 6], [8, 6, 9], [8, 1, 6], [7, 8, 9]]
Explanation : 4 rows of 3 length are randomly extracted.
Input : test_list = [6, 9, 1, 8, 4, 7], K, N = 2, 3
Output : [[7, 6], [7, 9], [1, 9]]
Explanation : 3 rows of 2 length are randomly extracted.
Method 1 : Using generator + shuffle()
In this, getting random elements is done using shuffle(), and yield with slicing is used to get K size of shuffled list.
Python3
# Python3 code to demonstrate working of
# K sized N random elements
# Using generator + shuffle()
from random import shuffle
# get random list
def random_list(sub, K):
while True:
shuffle(sub)
yield sub[:K]
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
# initializing K, N
K, N = 3, 4
# printing original list
print("The original list is : " + str(test_list))
res = []
# getting N random elements
for idx in range(0, N):
res.append(next(random_list(test_list, K)))
# printing result
print("K sized N random lists : " + str(res))
Output:
The original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[7, 1, 8], [8, 6, 1], [4, 9, 6], [6, 9, 1]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2 : Using product() + sample()
In this, all the possible permutations of K elements are extracted using product(), and from that random sampling of N lists are done.
Python3
# Python3 code to demonstrate working of
# K sized N random elements
# Using product() + sample()
from random import sample
import itertools
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
# initializing K, N
K, N = 3, 4
# printing original list
print("The original list is : " + str(test_list))
# get all permutations
temp = (idx for idx in itertools.product(test_list, repeat = K))
# get Random N from them
res = sample(list(temp), N)
res = list(map(list, res))
# printing result
print("K sized N random lists : " + str(res))
Output:
The original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[1, 1, 1], [6, 9, 4], [8, 7, 6], [4, 8, 8]]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. The product() + sample() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n), new list of size O(n) is created where n is the number of elements in the list
Method 3: Using combinations() and randint()
We can use the combinations() function from the itertools module to generate all possible combinations of K elements from the input list, and then use the randint() function from the random module to select N random combinations.
steps to implement this approach:
- Import the required modules:
- Define the function to generate K sized N random lists:
- Call the function with the input list, K and N:
Python3
from itertools import combinations
from random import randint
def random_lists(lst, K, N):
combos = list(combinations(lst, K))
rand_combos = [combos[randint(0, len(combos) - 1)] for i in range(N)]
return rand_combos
test_list = [6, 9, 1, 8, 4, 7]
K, N = 3, 4
res = random_lists(test_list, K, N)
print("K sized N random lists : " + str(res))
OutputK sized N random lists : [(9, 1, 8), (6, 8, 7), (6, 9, 4), (1, 8, 4)]
Time complexity: O(1)
Auxiliary space: O(N)
Method 5: Using random.sample() and slicing
- Import random module to use random.sample() method.
- Initialize the list of integers test_list.
- Initialize variables K and N.
- Print the original list.
- Use random.sample() method to get a random sample of K integers from test_list.
- Repeat the above step N times using a loop and append the result to a list.
- Print the final result.
Python3
import random
# Initializing list
test_list = [6, 9, 1, 8, 4, 7]
# Initializing K, N
K, N = 3, 4
# Printing original list
print("The original list is : " + str(test_list))
# Getting Random N lists of size K
res = []
for i in range(N):
res.append(random.sample(test_list, K))
# Printing result
print("K sized N random lists : " + str(res))
OutputThe original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[4, 6, 8], [1, 7, 4], [6, 9, 1], [1, 8, 7]]
Time Complexity: O(NK)
Auxiliary Space: O(NK)
Method 6: Using NumPy library
Python3
import numpy as np
# Initializing list
test_list = [6, 9, 1, 8, 4, 7]
# Initializing K, N
K, N = 3, 4
# Printing original list
print("The original list is: " + str(test_list))
# Get Random N lists of size K using NumPy
arr = np.array(test_list)
np.random.shuffle(arr) # Shuffle the array in-place
# Adjust the number of elements in arr to ensure equal division
num_elements = N * K
if num_elements > len(arr):
arr = np.tile(arr, num_elements // len(arr) + 1)[:num_elements]
res = np.split(arr, N)
# Converting NumPy arrays to nested lists
res = [sublist.tolist() for sublist in res]
# Printing result
print("K-sized N random lists: " + str(res))
OutputThe original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[4, 6, 8], [1, 7, 4], [6, 9, 1], [1, 8, 7]]
Time Complexity: O(N * K) since we still shuffle the array once and take the first N * K elements.
Auxiliary Space: O(N * K) as we need to store the shuffled array and the N subarrays.
Similar Reads
Python program to select Random value from list of lists
Given a list of lists. The task is to extract a random element from it. Examples: Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]] Output : 7 Explanation : Random number extracted from Matrix.Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]], r_no = 2 Output : 6 Explanation : Random number
4 min read
Python - Create List of Size n
Creating a list of size n in Python can be done in several ways. The easiest and most efficient way to create a list of size n is by multiplying a list. This method works well if we want to fill the list with a default value, like 0 or None.Python# Size of the list n = 5 # Creating a list of size n
2 min read
Python Program to Generate Random binary string
Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or
2 min read
Create List of Numbers with Given Range - Python
The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8
3 min read
Python List Creation Programs
Python provides multiple ways to create lists based on different requirements, such as generating lists of numbers, creating nested lists, forming lists of tuples or dictionaries, and more.This article covers various ways to create lists efficiently, including:Generating lists of numbers, strings, a
2 min read
Python Program For Selecting A Random Node From A Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator.Below is a Simple Solution: Count the number of nodes by traversing the list.Traverse the list again and s
4 min read
Python program to get all subsets of given size of a Set
We are given a set, and our task is to get all subsets of a given size. For example, if we have s = {1, 2, 3, 4} and need to find subsets of size k = 2, the output should be [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)].Using itertools.combinationsWe can use itertools.combinations(iterable, r) to
3 min read
Python Program to Construct dictionary using random values
Given List, our task is to write a Python program to construct a dictionary with values randomly selected from range. Examples: Input : test_list = ["Gfg", "is", "Best"], i, j = 2, 9 Output : {'Gfg': 3, 'is': 9, 'Best': 4} Explanation : Random values assigned between 2 and 9. Input : test_list = ["G
4 min read
Python List of List Programs
A list of lists is a common data structure in Python, used for handling multi-dimensional data, matrix operations and hierarchical data processing. Python provides several ways to manipulate and transform lists of lists, including sorting, merging, filtering and converting them into different format
2 min read
Python program to replace first 'K' elements by 'N'
Given a List, replace first K elements by N. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 Output : [3, 3, 3, 3, 4, 2, 6, 9] Explanation : First 4 elements are replaced by 3. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 Output : [10, 10, 6, 8, 4, 2, 6, 9] Explanation : Fi
5 min read