Dirk Li
Dirk Li

Reputation: 199

Why are for loop and np.random.shuffle not work as expected in Python?

I try to randomly shuffle the list in a for loop and then append it to another list. Expect to produce 5 lists in different orders, but the results are all in the same order. The code and output are as follows:

list_data = [] 
for i in range(10):
    list_data.append(i)
print(list_data)

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random_list = []
for j in range(5):
    np.random.shuffle(list_data)
    random_list.append(list_data)
    print(list_data)
print(random_list)

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

Upvotes: 1

Views: 466

Answers (1)

Péter Leéh
Péter Leéh

Reputation: 2119

Although you already have an answer I'd like to help you shorten it into 3 lines of code, and you don't need numpy either. This can be achieved by list comprehension. This code below does what you want. Note: I used random.sample instead of numpy.random.shuffle, because that shuffles the list inplace and returns None.

import random
list_data = [i for i in range(10)]
random_list = [random.sample(list_data, len(list_data)) for j in range(5)]

Upvotes: 1

Related Questions