07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

24 Chapter 1 ■ Introduction to Cryptography and Python

We will now take another look at tuples. As stated previously, tuples are

immutable, which means you cannot change them. You can only make a fresh

tuple and assign its reference to a previously used name:

>>> t = (23, 'abc', 4.56, (2,3), 'def')

>>> t[2] = 3.14

Traceback (most recent call last):

File "<pyshell#75>", line 1, in -topleveltu[

2] = 3.14

TypeError: object doesn't support item assignment

>>> t = (23, 'abc', 3.14, (2,3), 'def')

Lists, on the other hand, are mutable; this means we can change the lists

without having to reassign them. The variable will continue to point to the same

memory reference when the assignment is complete. The downside is that lists

are not as fast as tuples:

>>> li = ['abc', 23, 4.34, 23]

>>> li[1] = 45

>>> li

['abc', 45, 4.34, 23]

The following examples are operations that only apply to list objects:

>>> li = [1, 11, 3, 4, 5]

>>> li.append('a') # Our first exposure to method syntax

>>> li

[1, 11, 3, 4, 5, 'a']

>>> li.insert(2, 'i')

>>>li

[1, 11, 'i', 3, 4, 5, 'a']

Python has an extend() method that operates on lists in place; this operation

is different than the plus (+) operator, which creates a fresh list with a new

memory reference.

>>> li.extend([9, 8, 7])

>>>li

[1, 2, 'i', 3, 4, 5, 'a', 9, 8, 7]

You may find this a bit confusing as the extend() method takes a list as an

argument, whereas the append() method takes a singleton as an argument:

>>> li.append([10, 11, 12])

>>> li

[1, 2, 'i', 3, 4, 5, 'a', 9, 8, 7, [10, 11, 12]]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!