Shuffling a list - Answers
Q1. Get the code working:
import random
monsters=['witch','warlock','ghost','zombie','mummy','orc','evil monkey']
print(monsters)
for number in range(20):
random.shuffle(monsters)
print(monsters)
Q2. The code imports the random module. It then creates a list of monsters and prints it out. The code then shuffles this list and prints out the resulting shuffled list twenty times.
Q3. We now want to keep a copy of the original list in its original order. Type in the following code:
import random
monsters=['witch','warlock','ghost','zombie','mummy','orc','evil monkey']
print('\nThe original list is',monsters,'\n')
monsters_copy=monsters
for number in range(20):
random.shuffle(monsters_copy)
print(monsters_copy)
print('\nThe original list is',monsters)
This doesn't work. By using the line:
monsters_copy=monsters
we are just creating a new pointer to the same object. We have a single list object. It just has two different ways to access and change it. Reference to either pointer will still refer to the same object. This is why when we shuffle monsters_copy, and then examine monsters, we are going to see that the original order of monsters wasn't kept. A diagram can illustrate this:
Q4. The function id() can be used to return the unique ID of any object. By checking the ID of monsters and monsters_copy, we can prove they are the same. They are both just pointers to a single object list, which is why if you change the list using monsters_copy, the list pointed to by monsters also gets changed (because they are pointing to the same list!)
Q5 and Q6. The solution is actually very simple. We just need to copy a slice of the original list that contains all of the original list's elements:
import random
monsters=['witch','warlock','ghost','zombie','mummy','orc','evil monkey']
print('\nThe original list is',monsters,'\n')
monsters_copy=monsters[:]
print(id(monsters))
print(id(monsters_copy))
for number in range(20):
random.shuffle(monsters_copy)
print(monsters_copy)
print('\nThe original list is',monsters)
By using the id() function, we can see that monsters and monsters_copy are now completely separate objects.