+4 votes
in Programming Languages by (19.3k points)

I am trying to randomly select some elements from a list, but the code is giving an error. What's wrong with the following code?

random.shuffle(t)[:3]

>>> t

array([ 5,  3,  4, 13,  8,  9,  1,  6,  7,  2, 12, 11, 14, 10,  0])

>>> random.shuffle(t)[:3]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'NoneType' object is not subscriptable

1 Answer

0 votes
by (33.7k points)

The shuffle() function of "random" returns None. When you try to select 3 elements from the shuffled list, you are basically selecting from None, not from a list. Therefore, your code is giving the error.

You need first to shuffle the list and then select 3 elements from it.

Here is an example:

>>> import random
>>> t=[i for i in range(15)]
>>> t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> print(random.shuffle(t))
None

>>> random.shuffle(t)
>>> t
[6, 9, 13, 8, 5, 12, 7, 10, 1, 2, 14, 0, 4, 11, 3]
>>> t[:3]
[6, 9, 13]
>>>

...