Hacking Secret Ciphers with Python

(Ann) #1
Chapter 8 – The Transposition Cipher, Encrypting 109

A for loop can also iterate over the values in a list, just like it iterates over the characters in a
string. The value that is stored in the for loop’s variable is a single value from the list. Try
typing the following into the interactive shell:





for spam in ['aardvark', 'anteater', 'antelope', 'albert']:
... print('For dinner we are cooking ' + spam)





For dinner we are cooking aardvark
For dinner we are cooking anteater
For dinner we are cooking antelope
For dinner we are cooking albert








Using the list() Function to Convert Range Objects to Lists


If you need a list value that has increasing integer amounts, you could have code like this to build
up a list value using a for loop:





myList = []
for i in range(10):
... myList = myList + [i]
...
myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]





However, it is simpler to directly make a list from a range object that the range() function
returned by using the list() function:





myList = list(range(10))
myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]





The list() function can also convert strings into a list value. The list will have several single-
character strings that were in the original string:





myList = list('Hello world!')
myList
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']




Free download pdf