Vidar Trojenborg Vidar Trojenborg - 24 days ago 10
Python Question

Using shuffle method on list associated to another list shuffles them both?

This is my code

import random

#Creating a list
li1=[1,2,3,4,5,6,7,8,9]

#Creating a copy of li1 to li2
li2=li1

random.shuffle(li1)

print (li2)


This will also shuffle
li2
, why? Is there a way of shuffling them independently?

How can I solve this issue? Thank you very much!

Answer

When you do li2 = li1, you are not storing the copy of li1 but the reference of li1 list to li2.

In order to store the copy of li1 to li2, do:

li2 = l1[:]

# OR, via functional approach 
# li2 = list(li1)

Or, you may use copy.copy() as:

import copy
li2 = copy.copy(li1)

Sample Example:

>>> import random
>>> li1 = [1,2,3,4,5,6,7,8,9]
>>> li2 = li1[:]  # creating copy

# shuffling li1
>>> random.shuffle(li1)

>>> li1    # Shuffled content li1
[2, 1, 8, 6, 5, 4, 3, 9, 7]
>>> li2    # li2 holds the original copy
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> random.shuffle(li2)   # also shuffle li2
>>> li2
[1, 5, 8, 9, 7, 2, 4, 6, 3]
>>> li1
[2, 1, 8, 6, 5, 4, 3, 9, 7]
Comments