Hacking Secret Ciphers with Python

(Ann) #1

182 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The append() List Method


detectEnglish.py
42. if symbol in LETTERS_AND_SPACE:



  1. lettersOnly.append(symbol)


Line 42 checks if symbol (which is set to a single character on each iteration of line 41’s for
loop) exists in the LETTERS_AND_SPACE string. If it does, then it is added to the end of the
lettersOnly list with the append() list method.


If you want to add a single value to the end of a list, you could put the value in its own list and
then use list concatenation to add it. Try typing the following into the interactive shell, where the
value 42 is added to the end of the list stored in spam:





spam = [2, 3, 5, 7, 9, 11]
spam
[2, 3, 5, 7, 9, 11]
spam = spam + [42]
spam
[2, 3, 5, 7, 9, 11, 42]





When we add a value to the end of a list, we say we are appending the value to the list. This is
done with lists so frequently in Python that there is an append() list method which takes a
single argument to append to the end of the list. Try typing the following into the shell:





eggs = []
eggs.append('hovercraft')
eggs
['hovercraft']
eggs.append('eels')
eggs
['hovercraft', 'eels']
eggs.append(42)
eggs
['hovercraft', 'eels', 42]





For technical reasons, using the append() method is faster than putting a value in a list and
adding it with the + operator. The append() method modifies the list in-place to include the
new value. You should always prefer the append() method for adding values to the end of a
list.

Free download pdf