lagrange103
lagrange103

Reputation: 169

Python: shuffle within a for loop shuffles the same way every time

I have a list of numbers [1,2,3,4,5]. I would like to make a list, containing different permutations of [1,2,3,4,5] (i.e it would be a list of lists).

For example, I want something like [[1,4,5,3,2], [3,1,4,5,2],[ 5,1,2,4,3]].

import random
from random import shuffle

superlist = []
littlelist = [1,2,3,4,5]

for i in range(1, 4):
    random.shuffle(little_list)
    superlist.append(little_list)
print(superlist)

This outputs

[[2, 5, 4, 3, 1], [2, 5, 4, 3, 1], [2, 5, 4, 3, 1]]

So within my for loop, the 'random shuffle' produces the same thing. I tried time seeding it, but there was the same problem.

Upvotes: 1

Views: 1749

Answers (1)

Duncan
Duncan

Reputation: 95642

When you call random.shuffle you shuffle the list in place, you aren't making a copy. Then you append little_list to superlist but every time you shuffle it you are shuffling the same list.

Try appending a copy then you'll see the differences:

for i in range(1, 4):
    random.shuffle(little_list)
    superlist.append(list(little_list))
print(superlist)

Everything in Python works by manipulating references to objects: when you put an object (e.g. little_list) into another object all you are doing is making superlist hold a reference to the original little_list. Python never ever makes a copy of an object unless you specifically ask it to copy the object. You can copy a list easily by calling the list(...) constructor, but even that only copies the references from the original, so if you were to copy superlist and manipulate the lists it contains you would still see those changes back in the original superlist.

Upvotes: 6

Related Questions