Greck9
Greck9

Reputation: 29

How to iterate over list of lists and select random element in every list?

I have list of lists and I need to iterate over it and select one element in every list. And I need to do it 10 times. This is example of my code:

from itertools import chain
import random
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]

I tried:

for element in range(10):
    for element in list:
        res = random.choice(list(chain.from_iterable(test_list)))
        print("Random number from Matrix : " + str(res))

But I got error: 'type' object is not iterable

Upvotes: 1

Views: 786

Answers (3)

balderman
balderman

Reputation: 23815

something like the below

import random

test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]

for _ in range(10):
    for lst in test_list:
        print(lst[random.randint(0, len(lst) - 1)])

Upvotes: 1

Jasmijn
Jasmijn

Reputation: 10452

You don't need to chain here at all, because you're picking an item from each of the inner lists. Also, you're trying to iterate over list, which is a type, instead of test_list.

for _ in range(10):
    for inner_list in test_list:
        print("Random number from Matrix:", random.choice(inner_list))

Upvotes: 2

azro
azro

Reputation: 54148

Problems

  • you declare element twice as the iteration variable
  • you iterate on list which is a Python type, you need to iterate on test_list
  • you need to pick an element of the current sublist of the iteration, not the whole test_list

Solution

import random

test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]

for i in range(10):
    print(f"Round {i}")
    for sublist in test_list:
        res = random.choice(sublist)
        print("Random number from Matrix :", res)

Giving something like

Round 0
Random number from Matrix : 5
Random number from Matrix : 7
Random number from Matrix : 6
Round 1
Random number from Matrix : 5
Random number from Matrix : 4
Random number from Matrix : 8
Round 2
Random number from Matrix : 5
Random number from Matrix : 4
Random number from Matrix : 8
Round 3
Random number from Matrix : 5
Random number from Matrix : 7
Random number from Matrix : 3
...

Upvotes: 3

Related Questions