Module 2 Notes
Module 2 Notes
Python
Programming
MAY 10
SMVITM, Bantakal
by: Hithesh
1
Module 2: Lists
Lists: The List Data Type, Working with Lists, Augmented Assignment
Operators, Methods, Example Program: Magic 8 Ball with a List, List-like Types:
Strings and Tuples, References,
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing,
Using Data Structures to Model Real-World Things,
2
2.1 The List Data Type:
➢ A list spam = ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
➢ The Python code spam[0] would evaluate to 'cat',
➢ spam[1] would evaluate to 'bat', and so on.
➢ The integer inside the square brackets that follows the list is called an index.
➢ The first value in the list is at index 0, the second value is at index 1, the third value is at
index 2, and so on.
3
Figure 4-1 shows a list value assigned to spam, along with what the index expressions would
evaluate to.
For example, type the following expressions into the interactive shell.
➢ Notice that 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' .
➢ Python will give you an IndexError error message if you use an index that exceeds the
number of values in your list value.
4
Indexes can be only integer values, not floats. The following example will cause a TypeError error:
➢ The first index dictates which list value to use, and the second indicates the value within the
list value.
➢ For example, spam[0][1] prints 'bat', the second value in the first list.
➢ If you only use one index, the program will print the full list value at that index.
5
2.1.2 Negative Indexes
➢ While indexes start at 0 and go up, you 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.
Enter the following into the interactive shell:
➢ Just as an index can get a single value from a list, a slice can get several values from a list, in
the form of a new list.
➢ A slice is typed between square brackets, like an index, but it has two integers separated by
a colon.
➢ In a slice, the first integer is the index where the slice starts.
➢ The second integer is the index where the slice ends.
➢ A slice goes up to, but will not include, the value at the second index.
➢ A slice evaluates to a new list value.
6
Enter the following into the interactive shell:
➢ As a shortcut, you can leave out one or both of the indexes on either side of the colon in the
slice. [ :2], [2: ]
➢ Leaving out the first index is the same as using 0, or the beginning of the list.
➢ Leaving out the second index is the same as using the length of the list, which will slice to
the end of the list. Enter the following into the interactive shell:
7
2.1.4 Getting a List’s Length with len()
The len() function will return the number of values that are in a list value passed to it, just like it
can count the number of characters in a string value.
➢ Normally a variable name goes on the left side of an assignment statement, like spam = 42.
➢ However, you can also use an index of a list to change the value at that index.
➢ For example, spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to
the string 'aardvark'.”
Enter the following into the interactive shell:
8
2.1.6 List Concatenation and List Replication
➢ The + operator can combine two lists to create a new list value in the same way it combines
two strings into a new string value.
➢ The * operator can also be used with a list and an integer value to replicate the list.
9
2.2 Working with Lists
➢ When you first begin writing programs, it’s tempting to create many individual variables to
store a group of similar values.
➢ For example, if I wanted to store the names of my cats, I might be tempted to write code
like this:
Instead of using multiple, repetitive variables, you can use a single variable that contains a list
value.
For example,
List_1 = []
number = int(input( "Enter the number of cats you want to add: "))
print ("Enter cat's name: ")
for i in range(number):
n = input( "name : ")
List_1.append(n) # to add the number in the list
print("Cats name are: ", List_1)
OUTPUT:
Enter the number of cats you want to add: 4
Enter cat's name:
10
name : Ro
name : Li
name : Je
name : Ji
Cats name are: ['Ro', 'Li', 'Je', 'Ji']
for i in range(4):
print(i)
Output:
0
1
2
3
This is because the return value from range(4) is a list-like value that Python considers similar to
[0, 1, 2, 3].
The following program has the same output as the previous one:
for i in [0, 1, 2, 3]:
print(i)
Output:
0
1
2
3
A common Python technique is to use range(len(someList)) with a for loop to iterate over the
indexes of a list. For example, enter the following into the interactive shell:
11
➢ Using range(len(supplies)) in the previously shown for loop is handy because the code in
the loop can access the index (as the variable i) and the value at that index (as supplies[i]).
➢ Best of all, range(len(supplies)) will iterate through all the indexes of supplies, no matter
how many items it contains.
➢ You can determine whether a value is or isn’t in a list with the in and not in operators.
➢ Like other 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.
➢ These expressions will evaluate to a Boolean value.
12
Enter the following into the interactive shell
Example:
13
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z) # returns True because z is the same object as x
print(x is y) # returns False because x is not the same object as y, even if they have the same
content
print(x == y) # to demonstrate the difference between "is" and "==": this comparison returns True
because x is equal to y
OUTPUT:
True
False
True
is not operator
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z) # returns False because z is the same object as x
print(x is not y) # returns True because x is not the same object as y, even if they have the same
content.
print(x != y) # to demonstrate the difference between "is not" and "!=": this comparison returns
False because x is equal to y.
14
OUTPUT:
False
True
False
The multiple assignment trick is a shortcut that lets you assign multiple variables with the values
in a list in one line of code. So instead of doing this
The number of variables and the length of the list must be exactly equal, or Python will give you a
ValueError:
When assigning a value to a variable, you will frequently use the variable itself.
For example, after assigning 42 to the variable spam, you would increase the value in spam by 1
with the following code:
15
16
17
2.4 Methods
A method is the same thing as a function, except it is “called on” a value.
For example, if a list value were stored in spam, you would call the index() list method on that list
like so: spam.index('hello').
The method part comes after the value, separated by a period.
Each data type has its own set of methods.
The list data type, for example, has several useful methods for finding, adding, removing, and
otherwise manipulating values in a list.
Example:
fruits = ['apple', 'banana', 'cherry']
0 1 2
x = fruits.index("cherry")
print(x)
Output:
2
Example:
fruits = ['banana','apple','apple', 'cherry', 'apple']
x = fruits.index("apple")
print(x)
Output:
1
18
2. Insert Items - insert() method
➢ To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
➢ To insert a list item at a specified index, use the insert() method.
➢ The insert() method inserts an item at the specified index:
Syntax:
List_name. insert(index/Position, element)
Example:
thislist = ["apple", "banana", "cherry"]
thislist.insert(0, "watermelon")
print(thislist)
Output:
['watermelon','apple', 'banana', 'cherry']
Syntax:
List_name.append(element)
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)
19
Output:
['apple', 'banana', 'cherry',’orange’]
Syntax:
List_name.extend(another_List)
Example:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
output:
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
20
Output:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
spam.remove(‘chocolate')
ValueError: list.remove(x): x not in list
Syntax:
List_name.remove(element)
Example:
thislist = ["apple", "banana", "cherry", ‘banana’, ‘banana’]
thislist.remove("banana")
print(thislist)
Output:
['apple', 'cherry', ‘banana’, ‘banana’]
21
6. Remove Specified Index - pop() method:
➢ The pop() method removes the specified index.
➢ Removes the element at the specified position.
➢ If you do not specify the index, the pop() method removes the last item.
Syntax:
List_name. pop(index) thislist = ["apple", "banana", "cherry"]
thislist.pop()
Example: print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop(1) Output:
print(thislist) ["apple", "banana"]
Output:
['apple', 'cherry']
del keyword:
The del keyword also removes the specified
index.
The del keyword can also delete the list
completely.
Syntax:
del list_name[index]
del list_name
Example:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
thislist = ["apple", "banana", "cherry"]
del thislist
22
Output:
["banana", "cherry"]
7. Clear the List - clear() method
The clear() method empties the list.
The list still remains, but it has no content.
Syntax:
List_name.clear()
Example:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
output:
[]
➢ You can also pass True for the reverse keyword argument to have sort() sort the values in
reverse order.
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
23
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
There are three things you should note about the sort() method.
1. First, the sort() method sorts the list in place; don’t try to capture the return value by
writing code like spam = spam.sort().
2. Second, you cannot sort lists that have both number values and string values in them, since
Python doesn’t know how to compare these values.
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
Traceback (most recent call last): File "", line 1, in spam.sort()
TypeError: unorderable types: str() < int()
3. Third, sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting
strings.
This means uppercase letters come before lowercase letters. Therefore, the lowercase a is
sorted so that it comes after the uppercase Z.
>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
➢ If you need to sort the values in regular alphabetical order, pass str.lower for the ‘key’
keyword argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower) # converts strings to lower case
>>> spam
[‘a’, ‘A’, ‘z’, ‘Z’]
This causes the sort() function to treat all the items in the list as if they were lowercase without
actually changing the values in the list.
24
2.5 Example Program: Magic 8 Ball with a List
Using List:
import random
messages = ['It is certain’, 'It is decidedly so’, 'Yes definitely’, 'Reply hazy try again',
'Ask again later’, 'Concentrate and ask again’, 'My reply is no’, 'Outlook not so good’, 'Very
doubtful']
print(messages[random.randint(0, len(messages) - 1)])
➢ Notice 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.
➢ The benefit of this approach is that you can easily add and remove strings to the messages
list without changing other lines of code.
➢ If you later update your code, there will be fewer lines you have to change and fewer
chances for you to introduce bugs.
==========================================================================
25
Same program using Function (if - elif- else)
26
➢ For example, strings and lists are actually similar, if you consider a string to be a “list” of
single text characters.
➢ Many of the things you can do with lists can also be done with strings: indexing; slicing; and
using them with for loops, with len(), and with the in and not in operators.
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.
➢ Although a list value is mutable, the second line in the following code does not modify the
list eggs:
28
➢ you would have to do something like this:
29
2.8 The Tuple Data Type
The tuple data type is almost identical to the list data type, except in two ways.
First, tuples are typed with parentheses, ( ), instead of square brackets, [ ].
For example,
But the main way that tuples are different from lists is that tuples, like strings, are immutable.
➢ 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.
➢ Otherwise, Python will think you’ve just typed a value inside regular parentheses.
➢ The comma is what lets Python know this is a tuple value
>>> type(('hello',))
<class ‘tuple’>
30
>>> type(('hello'))
<class ‘str’>
31
2.9 Converting Types with the list() and tuple() Functions
➢ Just like how str(42) will return '42', the string representation of the integer 42,
➢ the functions list() and tuple() will return list and tuple versions of the values passed to
them.
➢ Enter the following into the interactive shell, and notice that the return value is of a
different data type than the value passed.
➢ Converting a tuple to a list is handy if you need a mutable version of a tuple value.
['cat', 'dog', 5]
<class ‘list’>
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
32
2.10 References
As you’ve seen, variables store strings and integer values.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
➢ You assign 42 to the spam variable, and then you copy the value in spam and assign it to
the variable cheese.
➢ When you 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.
33
➢ The code changed only the cheese list, but it seems that both the cheese and
spam lists have changed.
➢ When you create the list , you 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 you modify the first element of cheese , you are modifying the same
list that spam refers to.
34
Then, in Figure 4-5, the reference in spam is copied to cheese.
Only a new reference was created and stored in cheese, not a new list.
Note how both references refer to the same list
When you 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. You can see this in
Figure 4-6.
➢ Variables will contain references to list values rather than list values themselves.
➢ But for strings and integer values, variables simply 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.
35
2.10.1 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.
➢ For lists this means a copy of the reference is used for the parameter.
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
➢ Notice that when eggs() is called, a return value is not used to assign a new value
to spam.
➢ Instead, it modifies the list in place, directly.
➢ When run, this program produces the following output:
[1, 2, 3, 'Hello']
➢ 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.
Keep this behavior in mind: Forgetting that Python handles list and dictionary
variables this way can lead to confusing bugs.
36
2.10.2 The copy Module’s copy() and deepcopy() Functions
➢ Although passing around references is often the handiest way to deal with
lists and dictionaries, if the function modifies the list or dictionary that is
passed, you 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.
➢ 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 7.
➢ As you can see in Figure 4-7, the reference ID numbers are no longer the same
for both variables because the variables refer to independent lists.
37
If the list you need to copy contains lists, then use the copy.deepcopy() function
instead of copy.copy().
The deepcopy() function will copy these inner lists as well.
38