Skip to content
Related Articles
Open in App
Not now

Related Articles

Python program to select Random value form list of lists

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 16 Mar, 2023
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!