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.

Chapter 1 ■ Introduction to Cryptography and Python 25

Additionally, Python list objects can also use the index(), count(), remove(),

reverse(), and sort() methods as shown here:

>>> li = ['a', 'b', 'c', 'b']

>>> li.index('b') # index of first occurrence

1

>>> li.count('b') # number of occurrences

2

>>> li.remove('b') # remove first occurrence

>>> li

['a', 'c', 'b']

>>> li = [5, 2, 6, 8]

>>> li.reverse() # reverse the list *in place*

>>> li

[8, 6, 2, 5]

>>> li.sort() # sort the list *in place*

>>> li

[2, 5, 6, 8]

>>> li.sort(some_function) # sort in place using user-defined comparison

One thing to keep in mind when you are debating between using tuples

versus lists is that the list objects are slower but are more powerful than tuples.

Lists can be modified and have many operations that can be used on them. You

can convert between tuples and lists by using the list() and tuple() functions,

as shown here:

li = list(tu)

tu = tuple(li)

Dictionaries provide a way to store a mapping between a set of keys and a set

of values. The keys can be any immutable type, whereas the values can be any

type. A single dictionary can store a range of different types and allow you to

define, modify, view, look up, and delete a key-value pair within the dictionary.

Here is an example of a dictionary:

>>> d = {'user':'bozo', 'pswd':1234}

>>> d['user']

'bozo'

>>> d['pswd']

1234

>>> d['bozo']

Traceback (innermost last):

File '<interactive input>' line 1, in ?

KeyError: bozo

>>> d = {'user':'bozo', 'pswd':1234}

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

Saved successfully!

Ooh no, something went wrong!