Module 2 Pythonn
Module 2 Pythonn
CHAPTER 1: LISTS
A list begins with an opening square bracket and ends with a closing square bracket,
[].
Values inside the list are also called items and are separated with commas.
❶ is still assigned only one value: the list value(contains
multiple values).
The first value in the list is at index 0, the second value is at index 1, and the third
value is at index 2, and so on.
For example, type the following expressions into the interactive shell.
The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0]
evaluates to the string 'cat'. This expression in turn evaluates to the string value 'Hello
cat'.
If we use an index that exceeds the number of values in the list value then, python
gives IndexError.
Indexes can be only integer values, not floats. The following example will cause a
TypeError error:
Lists can also contain other list values. The values in these lists of lists can be
accessed using multiple indexes.
The first index dictates which list value to use, and the second indicates the value
within the list value. Ex, spam[0][1] prints 'bat', the second value in the first list.
Negative Indexes
We can also use negative integers for the index. The integer value -1 refers to the last
index in a list, the value -2 refers to the second-to-last index in a list, and so on.
A slice is typed between square brackets, like an index, but it has two integers
separated by a colon.
As a shortcut, we can leave out one or both of the indexes on either side of the
colon in the slice.
o Leaving out the first index is the same as using 0, or the beginning of the list.
o Leaving out the second index is the same as using the length of the list, which
will slice to the end of the list.
The len() function will return the number of values that are in a list value.
We can also use an index of a list to change the value at that index.
Ex: spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to the
string 'aardvark'.”
The * operator can also be used with a list and an integer value to replicate the list.
The del statement can also be used to delete a variable After deleting if we try to use
the variable, we will get a NameError error because the variable no longer exists.
In practice, you almost never need to delete simple variables.
The del statement is mostly used to delete values from lists.
Which is bad way to write code because it leads to have a duplicate code in the
program.
Instead of using multiple, repetitive variables, we can use a single variable that
contains a list value.
For Ex: The following program uses a single list and it can store any number of cats
that the user types in.
Program:
Output:
A for loop repeats the code block once for each value in a list or list-like value.
Program
Output:
A common Python technique is to use range (len(someList)) with a for loop to iterate
over the indexes of a list.
The code in the loop will access the index (as the variable i), the value at that index
(as supplies[i]) and range(len(supplies)) will iterate through all the indexes of
supplies, no matter how many items it contains.
We can determine whether a value is or isn’t in a list with the in and not in operators.
in and not in are used in expressions and connect two values: a value to look for in a
list and the list where it may be found and these expressions will evaluate to a
Boolean value.
The following program lets the user type in a pet name and then checks to see whether
the name is in a list of pets.
Program
Output
The Multiple Assignment Trick
The multiple assignment trick is a shortcut that lets you assign multiple variables with
the values in a list in one line of code.
When assigning a value to a variable, we will frequently use the variable itself
Instead of left-side program we could use right-side program i.e., with the augmented
assignment operator += to do the same thing as a shortcut.
The Augmented Assignment Operators are listed in the below table:
The += operator can also do string and list concatenation, and the *= operator can do
string and list replication.
1.4 Methods
A method is same as a function, except it is “called on” a value.
The method part comes after the value, separated by a period.
Each data type has its own set of methods.
The list data type has several useful methods for finding, adding, removing, and
manipulating values in a list.
Finding a Value in a List with the index() Method
List values have an index() method that can be passed a value, and if that value exists
in the list, the index of the value is returned. If the value isn’t in the list, then Python
produces a ValueError error.
When there are duplicates of the value in the list, the index of its first appearance is
returned.
The insert() method can insert a value at any index in the list. The first argument to
insert() is the index for the new value, and the second argument is the new value to be
inserted.
The append() and insert() methods are list methods and can be called only on list
values, not on other values such as strings or integers.
The remove() method is passed the value to be removed from the list it is called on.
Attempting to delete a value that does not exist in the list will result in a ValueError
error.
If the value appears multiple times in the list, only the first instance of the value will
be removed.
The del statement is good to use when you know the index of the value you want to
remove from the list. The remove() method is good when you know the value you
want to remove from the list.
Sorting the Values in a List with the sort() Method
Lists of number values or lists of strings can be sorted with the sort() method.
You can also pass True for the reverse keyword argument to have sort() sort the
values in reverse order.
There are three things you should note about the sort() method.
o First, the sort() method sorts the list in place; don’t try to return value by
writing code like spam = spam.sort().
o Second, we cannot sort lists that have both number values and string values in
them.
o Third, sort() uses “ASCIIbetical order(upper case)” rather than actual alphabetical
order(lower case) for sorting strings.
If we need to sort the values in regular alphabetical order, pass str.lower for the key
keyword argument in the sort() method call.
The expression you use as the index into messages: random .randint (0, len(messages)
- 1). This produces a random number to use for the index, regardless of the size of
messages. That is, you’ll get a random number between 0 and the value of
len(messages) - 1.
We can also split up a single instruction across multiple lines using the \ line
continuation character at the end.
The proper way to “mutate” a string is to use slicing and concatenation to build a new
string by copying from parts of the old string.
We used [0:7] and [8:12] to refer to the characters that we don’t wish to replace.
Notice that the original 'Zophie a cat' string is not modified because strings are
immutable.
List
A list value is a mutable data type: It can have values added, removed, or changed.
The list value in eggs isn’t being changed here; rather, an entirely new and different list
value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3]).
Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced with a
new list value.
If we want to modify the original list in eggs to contain [4, 5, 6], you would have to
delete the items in that and then add items to it.
Figure: The del statement and the append() method modify the same list value in place.
Second, benefit of using tuples instead of lists is that, because they are immutable and
their contents don’t change. Tuples cannot have their values modified, appended, or
removed.
If you have only one value in your tuple, you can indicate this by placing a trailing
comma after the value inside the parentheses.
The functions list() and tuple() will return list and tuple versions of the values passed
to them.
References
As , variables store strings and integer values.
We assign 42 to the spam variable, and then we copy the value in spam and assign it to
the variable cheese. When we later change the value in spam to 100, this doesn’t affect
the value in cheese. This is because spam and cheese are different variables that store
different values.
But lists works differently. When we assign a list to a variable, we are actually
assigning a list reference to the variable. A reference is a value that points to some bit
of data, and a list reference is a value that points to a list.
When we create the list ❶, we assign a reference to it in the spam variable. But the
next line copies only the list reference in spam to cheese, not the list value itself. This
means the values stored in spam and cheese now both refer to the same list.
There is only one underlying list because the list itself was never actually copied. So
when we modify the first element of cheese, we are modifying the same list that spam
refers to.
List variables don’t actually contain lists—they contain references to lists.
Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.
The reference in spam is copied to cheese. Only a new reference was created and
stored in cheese, not a new list.
When we alter the list that cheese refers to, the list that spam refers to is also changed,
because both cheese and spam refer to the same list.
Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to
Variables will contain references to list values rather than list values themselves.
But for strings and integer values, variables will contain the string or integer value.
Python uses references whenever variables must store values of mutable data types,
such as lists or dictionaries. For values of immutable data types such as strings,
integers, or tuples, Python variables will store the value itself.
Passing References
References are particularly important for understanding how arguments get passed to
functions.
When a function is called, the values of the arguments are copied to the parameter
variables.
Program Output
when eggs() is called, a return value is not used to assign a new value to spam.
Even though spam and someParameter contain separate references, they both refer to
the same list. This is why the append('Hello') method call inside the function affects
the list even after the function call has returned
The copy Module’s copy() and deepcopy() Functions
If the function modifies the list or dictionary that is passed, we may not want these
changes in the original list or dictionary value.
For this, Python provides a module named copy that provides both the copy() and
deepcopy() functions.
copy(), can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
Now the spam and cheese variables refer to separate lists, which is why only the list
in cheese is modified when you assign 42 at index 1.
The reference ID numbers are no longer the same for both variables because the
variables refer to independent lists
Figure: cheese = copy.copy(spam) creates a second list that can be modified independently of
the first.
copy function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.copy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
1498111334272
1498110961152
deepcopy() Function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.deepcopy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
1498111298880
1498111336064
2. Pretty Printing
This assigns a dictionary to the myCat variable. This dictionary’s keys are 'size',
'color', and 'disposition'. The values for these keys are 'fat', 'gray', and 'loud',
respectively. You can access these values through their keys:
Dictionaries can still use integer values as keys, but they do not have to start at 0 and
can be any number.
Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, much like a list’s “out-of-range” IndexError error message.
We can have arbitrary values for the keys that allows us to organize our data in
powerful ways.
Ex: we want to store data about our friends’ birthdays. We can use a dictionary with
the names as keys and the birthdays as values.
Program:
Output:
There are three dictionary methods that will return list-like values of the dictionary’s
keys, values, or both keys and values: keys(), values(), and items().
Data types (dict_keys, dict_values, and dict_items, respectively) can be used in for
loops
A for loop can iterate over the keys, values, or key-value pairs in a dictionary by using
keys(), values(), and items() methods.
The values in the dict_items value returned by the items() method are tuples of the
key and value.
If we want a true list from one of these methods, pass its list-like return value to the
list() function.
The list(spam.keys()) line takes the dict_keys value returned from keys() and passes it
to list(), which then returns a list value of ['color', 'age'].
We can also use the multiple assignment trick in a for loop to assign the key and value
to separate variables.
We can use the in and not in operators to see whether a certain key or value exists in
a dictionary
The first time setdefault() is called, the dictionary in spam changes to {'color': 'black',
'age': 5, 'name': 'Pooka'}. The method returns the value 'black' because this is now the
value set for the key 'color'. When spam.setdefault('color', 'white') is called next, the
value for that key is not changed to 'white' because spam already has a key named
'color'.
Ex: program that counts the number of occurrences of each letter in a string.
The program loops over each character in the message variable’s string, counting how
often each character appears.
The setdefault() method call ensures that the key is in the count dictionary (with a
default value of 0), so the program doesn’t throw a KeyError error when
count[character] = count[character] + 1 is executed.
Output:
Importing pprint module will provide access to the pprint() and pformat() functions
that will “pretty print” a dictionary’s values.
This is helpful when we want a cleaner display of the items in a dictionary than what
print() provides and also it is helpful when the dictionary itself contains nested lists or
dictionaries..
Program: counts the number of occurrences of each letter in a string.
Output:
A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can each
contain an X, an O, or a blank. To represent the board with a dictionary, we can
assign each slot a string-value key as shown in below figure.
We can use string values to represent what’s in each slot on the board: 'X', 'O', or ' ' (a
space character).
To store nine strings. We can use a dictionary of values for this.
o The string value with the key 'top-R' can represent the top-right corner,
o The string value with the key 'low-L' can represent the bottom-left corner,
o The string value with the key 'mid-M' can represent the middle, and so on.
Store this board-as-a-dictionary in a variable named theBoard.
The data structure stored in the theBoard variable represents the tic-tactoe board in the
below Figure.
Since the value for every key in theBoard is a single-space string, this dictionary
represents a completely clear board. If player X went first and chose the middle space,
you could represent that board with this dictionary as shown below:
The data structure in theBoard now represents tic-tac-toe board in the below Figure.
The player sees only what is printed to the screen, not the contents of variables.
The tic-tac-toe program is updated as below.
Output:
The printBoard() function can handle any tic-tac-toe data structure you pass it.
Program
Output:
Now we created a data structure to represent a tic-tac-toe board and wrote code in
printBoard() to interpret that data structure, we now have a program that “models” the
tic-tac-toe board.
Program: allows the players to enter their moves.
Output:
.
Inside the totalBrought() function, the for loop iterates over the keyvalue pairs in
guests 1.
Inside the loop, the string of the guest’s name is assigned to k, and the dictionary of
picnic items they’re bringing is assigned to v.
If the item parameter exists as a key in this dictionary, it’s value (the quantity) is
added to numBrought 2.
If it does not exist as a key, the get() method returns 0 to be added to numBrought.
Output:
But we want to use either double or single quotes within a string then we have a
multiple ways to do it as shown below.
Double Quotes
One benefit of using double quotes is that the string can have a single quote character in
it.
Since the string begins with a double quote, Python knows that the single quote is part
of the string and not marking the end of the string.
Escape Characters
If you need to use both single quotes and double quotes in the string, you’ll need to
use escape characters.
An escape character consists of a backslash (\) followed by the character you want to
add to the string.
Python knows that the single quote in Bob\'s has a backslash, it is not a single quote
meant to end the string value. The escape characters \' and \" allows to put single
quotes and double quotes inside your strings, respectively.
Ex:
The different special escape characters can be used in a program as listed below in a
table.
Raw Strings
You can place an r before the beginning quotation mark of a string to make it a raw
string. A raw string completely ignores all escape characters and prints any backslash
that appears in the string
Output
The following print() call would print identical text but doesn’t use a multiline string.
Multiline Comments
While the hash character (#) marks the beginning of a comment for the rest of the
line.
A multiline string is often used for comments that span multiple lines.
Strings use indexes and slices the same way lists do. We can think of the string 'Hello
world!' as a list and each character in the string as an item with a corresponding index.
The space and exclamation point are included in the character count, so 'Hello world!'
is 12 characters long.
If we specify an index, you’ll get the character at that position in the string.
If we specify a range from one index to another, the starting index is included and the
ending index is not.
The substring we get from spam[0:5] will include everything from spam[0] to
spam[4], leaving out the space at index 5.
The in and not in Operators with Strings
The in and not in operators can be used with strings just like with list values.
An expression with two strings joined using in or not in will evaluate to a Boolean
True or False.
These expressions test whether the first string (the exact string, case sensitive) can be
found within the second string.
The upper() and lower() string methods return a new string where all the letters in the
original string have been converted to uppercase or lowercase, respectively.
These methods do not change the string itself but return new string values.
If we want to change the original string, we have to call upper() or lower() on the
string and then assign the new string to the variable where the original was stored.
The upper() and lower() methods are helpful if we need to make a case-insensitive
comparison.
In the following small program, it does not matter whether the user types Great,
GREAT, or grEAT, because the string is first converted to lowercase.
Program Output
The isupper() and islower() methods will return a Boolean True value if the string has
at least one letter and all the letters are uppercase or lowercase, respectively.
Otherwise, the method returns False.
Since the upper() and lower() string methods themselves return strings, you can call
string methods on those returned string values as well. Expressions that do this will
look like a chain of method calls.
The isX string methods are helpful when you need to validate user input.
For example, the following program repeatedly asks users for their age and a
password until they provide valid input.
Program output
These methods are useful alternatives to the == equals operator if we need to check
only whether the first or last part of the string, rather than the whole thing, is equal to
another string.
The join() method is useful when we have a list of strings that need to be joined
together into a single string value.
The join() method is called on a string, gets passed a list of strings, and returns a
string. The returned string is the concatenation of each string in the passed-in list.
string join() calls on is inserted between each string of the list argument.
o Ex: when join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string is
'cats, rats, bats'.
o join() is called on a string value and is passed a list value.
Split()
The split() method is called on a string value and returns a list of strings.
We can pass a delimiter string to the split() method to specify a different string to split
upon.
common use of split() is to split a multiline string along the newline characters.
Passing split() the argument '\n' lets us split the multiline string stored in spam along
the newlines and return a list in which each item corresponds to one line of the string.
Justifying Text with rjust(), ljust(), and center()
The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
The first argument to both methods is an integer length for the justified string.
'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10.
'Hello' is five characters, so five spaces will be added to its left, giving us a string of
10 characters with 'Hello' justified right.
An optional second argument to rjust() and ljust() will specify a fill character other
than a space character.
The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.
These methods are especially useful when you need to print tabular data that has the
correct spacing.
In the below program, we define a printPicnic() method that will take in a dictionary
of information and use center(), ljust(), and rjust() to display that information in a
neatly aligned table-like format.
o The dictionary that we’ll pass to printPicnic() is picnicItems.
o In picnicItems, we have 4 sandwiches, 12 apples, 4 cups, and 8000 cookies.
We want to organize this information into two columns, with the name of the
item on the left and the quantity on the right.
Program output
Optionally, a string argument will specify which characters on the ends should be
stripped.
Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and
capital S from the ends of the string stored in spam.
The order of the characters in the string passed to strip() does not matter: strip('ampS')
will do the same thing as strip('mapS') or strip('Spam').
Copying and Pasting Strings with the pyperclip Module
The pyperclip module has copy() and paste() functions that can send text to and
receive text from your computer’s clipboard.
Of course, if something outside of your program changes the clipboard contents, the
paste() function will return it.
The password manager program you’ll create in this example isn’t secure, but it offers
a basic demonstration of how such programs work.
This new code looks in the PASSWORDS dictionary for the account name. If the
account name is a key in the dictionary, we get the value corresponding to that key,
copy it to the clipboard, and print a message saying that we copied the value.
Otherwise, we print a message saying there’s no account with that name.
On Windows, you can create a batch file to run this program with the win-R Run
window. Type the following into the file editor and save the file as pw.bat in the
C:\Windows folder:
With this batch file created, running the password-safe program on Windows is just a
matter of pressing win-R and typing pw <account name>.
3.4 Project: Adding Bullets to Wiki Markup
When editing a Wikipedia article, we can create a bulleted list by putting each list
item on its own line and placing a star in front.
But say we have a really large list that we want to add bullet points to. We could just
type those stars at the beginning of each line, one by one. Or we could automate this
task with a short Python script.
The bulletPointAdder.py script will get the text from the clipboard, add a star and
space to the beginning of each line, and then paste this new text to the clipboard.
Ex:
Program output
We split the text along its newlines to get a list in which each item is one line of the
text. For each line, we add a star and a space to the start of the line. Now each string
in lines begins with a star
Step 3: Join the Modified Lines
The lines list now contains modified lines that start with stars.
pyperclip.copy() is expecting a single string value, not a list of string values. To make
this single string value, pass lines into the join() method to get a single string joined
from the list’s strings.
When this program is run, it replaces the text on the clipboard with text that has stars
at the start of each line.