Open In App

Python program to select Random value from list of lists

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 extracted from 2nd row from Matrix.

Method #1: Using chain.from_iterable() + random.choice()

In this, we flatten the Matrix to list using from_iterable() and choice() is used to get a random number from the list.

Python3




# Python3 code to demonstrate working of
# Random Matrix Element
# Using chain.from_iterables() + random.choice()
from itertools import chain
import random
 
# Initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# choice() for random number, from_iterables for flattening
res = random.choice(list(chain.from_iterable(test_list)))
 
# Printing result
print("Random number from Matrix : " + str(res))


Output

The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix : 6

Method #2 : Using choice() to get element from particular row

If a row is mentioned, the choice() method can be used to get a random element from that row.

Python3




# Python3 code to demonstrate working of
# Random Matrix Element
# Using random.choice() [if row number given]
import random
 
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Row number
r_no = [0, 1, 2]
 
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[random.choice(r_no)])
 
# printing result
print("Random number from Matrix Row : " + str(res))


Output

The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix Row : 7

Method 3: Using the numpy package. 

Approach:

  1. Import the numpy package.
  2. Initialize the 2D matrix using the numpy array() method.
  3. Use the numpy random.choice() method to generate a random number from the matrix.
  4. Print the result.

Python3




import numpy as np
import random
 
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Row number
r_no = [0, 1, 2]
 
# Converting list to numpy array
arr = np.array(test_list)
 
# Generating random number from matrix
# using numpy random.choice() method
res = np.random.choice(arr[random.choice(r_no)])
 
# Printing result
print("Random number from Matrix Row : " + str(res))


Output

The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix Row : 7

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3 : Using list comprehension and random.sample()

Approach:

  1. Import the random module
  2. Initialize the list and print the original list
  3. Generate a random number for the row index using random.randint() method
  4. Use list comprehension to extract the row corresponding to the random index generated in step 3
  5. Use the random.sample() method to get a sample of elements from the row, with a sample size of 1.
  6. Get the randomly selected element from the sample and store it in a variable.
  7. Print the randomly selected element from the matrix row.

Python3




import random
 
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# generating random row index
row_index = random.randint(0, len(test_list)-1)
 
# extracting the row corresponding to the random index using list comprehension
row = [test_list[row_index][i] for i in range(len(test_list[row_index]))]
 
# getting a sample of elements from the row using random.sample()
sample = random.sample(row, k=1)
 
# getting the randomly selected element from the sample
res = sample[0]
 
# printing result
print("Random number from Matrix Row : " + str(res))


Output

The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix Row : 7

Time Complexity: O(n) – linear time complexity as we are traversing the matrix once using list comprehension to extract the row.
Auxiliary Space: O(n) – linear auxiliary space as we are creating a new list to store the extracted row.



Similar Reads

Python | Select random value from a list
Given a list and our task is to randomly select elements from the list in Python using various functions. Selecting random numbers from a list can be used sometimes while building games, choosing a random range, etc. Example Input: [2, 3, 4 , 5, 6 ] Output: 2 Explaination:The output we are getting is a random value from the input listSelect the Ran
5 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python program to convert a list into a list of lists using a step value
Given a List, the task here is to write a python program that can split the list into list of lists using by a step value here denoted via K. Input : test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8], K = 3Output : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]Explanation : 5, 2 and 9 are 0th, 3rd and 6th element respectively, and hence ( difference 3 ) grouped togethe
4 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 min read
Select Random Element from Set in Python
Selecting a random element from a group of samples is a deterministic task. A computer program can mimic such a simulation of random choices by using a pseudo-random generator. In this article, we will learn how to select a random element from a set in Python. What is a Set in Python?A Set is an unordered collection of elements that are iterable, m
3 min read
How to Select a Random Element from a Tuple in Python
Selecting a random element consists of retrieving one element from a collection in an unpredictable manner. In Python, this can be done easily using different methods provided by the random module. Below are the three different approaches to select a random element from a tuple. Select a Random Element from a Tuple in PythonBelow are the possible a
2 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read