1

I have a list of 10 x 10, with objects like this:

self.taula = [[casella() for i in range(10)] for j in range(10)]

How do I select a random object from this list?

I've been trying but of course I don't have any integer to use as an index, I'm pretty new to coding so I might be doing something wrong.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 2
    Use [`random.choice()`](https://docs.python.org/3/library/random.html#random.choice) – Michael Ruth Oct 22 '22 at 18:45
  • 1
    You could [make a flat version of the list](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists) and then use `random.choice`. – Stuart Oct 22 '22 at 18:49

1 Answers1

6

Assuming you want to select a random single element, you can use random.choice twice: first to select a list within the list of lists at random, then to randomly choose from that list.

import random

rand = random.choice(random.choice(self.taula))

Note this works well when the nested lists are of equal length as each individual element has an equal likelihood of being randomly selected. However, if they are uneven, as in the below example, it does affect the randomness of the selection.

[
  [1, 2, 3],
  [4, 5, 6, 7, 8, 9, 10],
  [0]
]

0 has a 1-in-3 chance of being picked, but 10 has a 1-in-21 chance of being picked.

To address this, you can flatten the list, and then choose from that.

flat = [y for x in self.taula for y in x]

random.choice(flat)
Chris
  • 26,361
  • 5
  • 21
  • 42