+2 votes
in Programming Languages by (74.2k points)
I want to create a python list with elements 1..15, but these numbers should be in random order. e.g. [3,15,10,4....]. What is the best Pythonic way to get this result?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use shuffle() function of random or permutation() function of numpy.random. See the following examples:

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

For shuffle(), you need to declare the list first, but for permutation, you don't have to declare the list in advance.


...