Back

Shuffling a list

Q1. Get this 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. Describe what the code does.
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)

Does this do what we set out to do?

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 see they are indeed 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!)

Enter this code and examine the ID of monsters and monsters_copy and observe they are the same:

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)

Q5. Using the Internet, find out how to make a copy of a list successfully, so that if you modify the copy, the original list is not modified as well.
Q6. Once you have figured out how to copy a list, so you have two completely independent lists, print their ID numbers and check that they are indeed different.

Back