As I wrote a bit of code tonight, I came across a problem that even though it doesn’t stop me, caught my attention for I couldn’t figure it out. So here’s a function I wrote (not supposed to be the optimal way to do it but nevermind…)
def ownShuffle( origin ):
export = [[] for i in range( len( origin ) ) ]
indices = range( len( origin ) )
for n, item in enumerate( origin ):
i = random.randrange( len( indices ) )
export[indices[i]] = item
indices.remove(indices[i])
return export
Now with a test sample like this:
c = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
There is the problem part. I get different results with the almost same code.
If it write this:
for i, line in enumerate(c):
c[i] = ownShuffle(line)
print c
>>> [[3, 2, 1],
[6, 4, 5],
[7, 8, 9]]
I get a shuffled list. But with the following code:
for i, line in enumerate(c):
line = ownShuffle(line)
print c
>>> [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
I get the test sample unchanged. Perhaps it comes from the function I wrote? I have no idea…
So there goes my question: Does anyone know why?
Thank you 🙂
You keep creating a temporary
linebut its not the same reference as your original listc. You would actually need to affect the values inside oflinefor it to reflect the original object.You could see it changing the values inside of that same
lineby doing:Here is a way to visualize what is happening:
In the first one you can see that its always a temporary object. Whereas in the second, the line is still the original line element from your
c