Skip to content
Related Articles

Related Articles

Improve Article

Python program to select Random value form list of lists

  • Last Updated : 05 Sep, 2020

Given a list of lists. The task is to extract a random element from it.

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 = 1
  
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[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
Recommended Articles
Page :