Vic Nicethemer
Vic Nicethemer

Reputation: 1111

Random.shuffle surprisingly doesn't work inside loop

Random.shuffle surprisingly doesn't work inside loop, it always produce the same shuffled list, but i need 19 different lists in order:

for i in range(19):
    random.seed() #random.randint(1, 50)
    random.shuffle(candidates_random_list)
    random.seed()
    candidates_full_list.append(candidates_random_list)
print('candidates_full_list ----- \n\n ')
pprint(candidates_full_list)

I saw a lot of tutorials and expected seed() will solve this, but it is in my opinion misbehavior. Every run it shuffle, but not in loop.

Upvotes: 1

Views: 255

Answers (1)

chepner
chepner

Reputation: 530960

shuffle is in-place, and your list contains 19 references to the same list, not separate lists resulting from each shuffle.

Store a copy of the shuffled list instead.

for i in range(19):
    random.shuffle(candidates_random_list)
    candidates_full_list.append(candidates_random_list[:])

Upvotes: 3

Related Questions