Hacking Secret Ciphers with Python

(Ann) #1

148 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The copy.deepcopy() function isn’t used in this chapter’s program, but it is helpful when
you need to make a duplicate list value to store in a different variable.


Practice Exercises, Chapter 10, Set A


Practice exercises can be found at http://invpy.com/hackingpractice 10 A.


The random.shuffle() Function


The random.shuffle() function is also in the random module. It accepts a list argument,
and then randomly rearranges items in the list. Type the following into the interactive shell:





import random
spam = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
spam
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(spam)
spam
[3, 0, 5, 9, 6, 8, 2, 4, 1, 7]
random.shuffle(spam)
spam
[1, 2, 5, 9, 4, 7, 0, 3, 6, 8]





An important thing to note is that shuffle() does not return a list value. Instead, it changes
the list value that is passed to it (because shuffle() modifies the list directly from the list


reference value it is passed.) We say that the shuffle() function modifies the list in-place.
This is why we only need to execute random.shuffle(spam) instead of spam =
random.shuffle(spam).


Remember that you can use the list() function to convert a string or range object to a list
value. Type the following into the interactive shell:





import random
eggs = list('Hello')
eggs
['H', 'e', 'l', 'l', 'o']
random.shuffle(eggs)
eggs
['o', 'H', 'l', 'l', 'e']




Free download pdf