0% found this document useful (0 votes)
2 views143 pages

Understanding Python Lists and Usage

The document provides an overview of lists in Python, detailing their characteristics such as being ordered, changeable, and allowing duplicate values. It explains how to create lists, access items, modify values, and perform operations like concatenation and deletion. Additionally, it covers the use of loops with lists and demonstrates various list functionalities through examples.

Uploaded by

ajayishereaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views143 pages

Understanding Python Lists and Usage

The document provides an overview of lists in Python, detailing their characteristics such as being ordered, changeable, and allowing duplicate values. It explains how to create lists, access items, modify values, and perform operations like concatenation and deletion. Additionally, it covers the use of loops with lists and demonstrates various list functionalities through examples.

Uploaded by

ajayishereaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Lists

BY,
HITHESH M
ASST. PROFESSOR
DEPT. OF. MECH
SMVITM - BANTAKAL
2
Introduction

 Lists and tuples can contain multiple values, which makes it easier to write programs that
handle large amounts of data.

 And since lists themselves can contain other lists, you can use them to arrange data into
hierarchical structures.

 Lists are used to store multiple items in a single variable.

 Lists are one of 4 built-in data types in Python used to store collections of data, the other
3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
3
Lists are created using square brackets:

thislist = ["apple", "banana", "cherry"]


print(thislist)

OUTPUT:
['apple', 'banana', 'cherry']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
4
List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered:
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
5

Changeable: The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates: Since lists are indexed, lists can have items with the same
value:
Example: Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
Output:
print(thislist)
['apple', 'banana', 'cherry', 'apple',
'cherry'] 11/07/2025
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
List Length/Getting a List’s Length 6
with len()

To determine how many items a list has, use the len() function:
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

Output:3

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
7
List Items - Data Types

 List items can be of any data type:


 String, int and Boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
['apple', 'banana',
list3 = [True, False, False]
'cherry’]
[1, 5, 7, 9, 3]
[True, False, False]
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
8
A list can contain different data
types:
A list with strings, integers and Boolean values:
list1 = ["abc", 34, True, 40, "male"]

['abc', 34, True, 40, 'male']

>>> ['hello', 3.1415, True, None, 42]

['hello', 3.1415, True, None, 42]


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
9
type()

 From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>

What is the data type of a list?

mylist =
["apple", "banana", "cherry"]
print(type(mylist))
<class
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
10
The list() Constructor

 It is also possible to use the list() constructor when creating a


new list.

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets

print(thislist) OUTPUT:

['apple', 'banana', 'cherry']


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
11
Python - Access List Items

 List
items are indexed and you can access them by referring to the index
number:

Print the second item of the list:

thislist = ["apple", “Mango", "cherry"]


print(thislist[1])
OUTPUT: Mango
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Print the last item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
OUTPUT:
Shri Madhwa Vadiraja Institute of Technology and Manage
cherry 11/07/2025
ment
13
Range of Indexes/Getting Sublists with
Slices
 You can specify a range of indexes by specifying where to start and where to end the range.
 When specifying a range, the return value will be a new list with the specified items.

 Example: Return the third, fourth, and fifth item:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
#This will return the items
print(thislist[2:5])# isfrom position
a list with2 to
a slice (two integers).
OUTPUT:
5.
#Remember that the first item is position 0, ['cherry', 'orange', 'kiwi']
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
14

Note: The search will start at index 2


(included) and end at index 5 (not included).

Remember that the first item has index 0.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
15

 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.
Notice the difference between indexes and slices.
• spam[2] is a list with an index (one integer).
• spam[1:4] is a list with a slice (two integers).
 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.
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
16

 >>> spam = ['cat', 'bat', 'rat', 'elephant']


 >>> spam[0:4]
['cat', 'bat', 'rat', 'elephant’]

 >>> spam[1:3]
['bat', 'rat’]

 >>> spam[0:-1]
['cat', 'bat', 'rat']
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
11/07/2025
17
By leaving out the start value, the range will
start at the first item:

Example
 This example returns the items from the beginning to, but NOT including, "kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])
OUTPUT:
['apple', 'banana', 'cherry', 'orange']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
18
By leaving out the end value, the range will
go on to the end of the list:

Example

 This example returns the items from "cherry" to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])
OUTPUT:
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
19
Range of Negative Indexes

 Specify negative indexes if you want to start the search from


the end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT including "mango"
(-1):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
OUTPUT:
['orange', 'kiwi', 'melon']
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
20
Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist: OUTPUT:
Yes, 'apple' is in the fruits
print("Yes, 'apple' is in the fruits list")
Shri Madhwa Vadiraja Institute of Technology and Manage
list 11/07/2025
ment
Change List Items/Changing 21
Values in a List with Indexes

Change Item Value


 To change the value of a specific item, refer to the index number:

Change the second item:

thislist =
["apple", "banana", "cherry"]
thislist[1] = "blackcurrant" Output:
['apple', 'blackcurrant',
print(thislist) 11/07/2025
Shri Madhwa Vadiraja Institute of Technology and Manage
ment 'cherry']
22
Change a Range of Item Values

 To change the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new
values:
Example: Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi',
'mango']
print(thislist)
Shri Madhwa Vadiraja Institute of Technology and
Management 11/07/2025
23
If you insert more items than you replace, the new items
will be inserted where you specified, and the remaining
items will move accordingly:

Example
 Change the second value by replacing it with two new values:

thislist = ["apple", “GreenApple", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
['apple', 'blackcurrant', 'watermelon',
'cherry']
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
24

 Note: The length of the list will change when the number of
items inserted does not match the number of items replaced.

 Ifyou insert less items than you replace, the new items will
be inserted where you specified, and the remaining items will
move accordingly:

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
25

Example
 Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)
OUTPUT:
Shri Madhwa Vadiraja Institute of Technology and Manage ['apple', 'watermelon’] 11/07/2025
ment
26
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.
 Example:

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
27

>>> [1, 2, 3] + ['A', 'B', 'C’] >>> spam = [1, 2, 3]


>>> spam = spam + ['A', 'B',
[1, 2, 3, 'A', 'B', 'C’]
'C']
>>> spam
>>> ['X', 'Y', 'Z'] * 3

[1, 2, 3, 'A', 'B', 'C']


['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z’]
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
28
Removing Values from Lists with del
Statements

 Remove Specified Item


The del statement will delete values at an index in a list.
All of the values in the list after the deleted value will be moved up one index.

>>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> del spam[2]


>>> del spam[2] >>> spam
>>> spam
['cat', 'bat']
['cat', 'bat', 'elephant’]

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
29

The del keyword removes the specified index: Ex3

Remove the first item:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist) OUTPUT:
['banana', 'cherry']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
30
The del keyword can also delete the list completely.

 Delete the entire list:

thislist = ["apple", "banana", "cherry"]


del thislist

OUTPUT:
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
31

Traceback (most recent call last):

File "demo_list_del2.py", line 3, in <module>

print(thislist) #this will cause an error


because you have succsesfully deleted "thislist".

NameError: name 'thislist' is not defined

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
32
Using for Loops with Lists

 For loop repeats the code block once for each value in a list or list-like value.

for i in range(4): the output of this program would be as


follows:
print(i) 0 This is because the return value from range(4) is a list-like
1
2
value that Python considers similar to [0, 1, 2, 3].
3
The following program has the same output as the
previous one:

for i in [0, 1, 2, 3]: What the previous for loop actually does is loop through its clause with
print(i) the variable i set to a successive value in the [0, 1, 2, 3] list in each
iteration
Shri Madhwa Vadiraja Institute
ment
of Technology and Manage 11/07/2025
33

A common Python technique is to use range(len(someList)) with a for loop to iterate over
the indexes of a list.
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])

OUTPUT:
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Shri Madhwa Vadiraja Institute of Technology and Manage
ment Index 3 in supplies is: binders 11/07/2025
34

 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.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
35
More Examples

You can also loop through the list items by referring to their
index number.
Use the range() and len() functions to create a suitable iterable.
Print all items by referring to their index number:

apple
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)): banana
print(thislist[i]) cherry
Shri Try itVadiraja
Madhwa Yourself
Institute of Technology and Manage 11/07/2025
ment
36
Python Operators

 Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values: print(10 + 5)
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
37
Python Arithmetic Operators

 Arithmetic operators are used with numeric values to perform common


mathematical operations:

x=5 x=5 x=5 x = 12 x=5 x=2


y=3 y=3 y=3 y=3 y=2 y=5
print(x + print(x - y) print(x * y)print(x / y) print(x % y) print(x ** y)
y) OUTPUT: 2 OUTPUT: 15OUTPUT: 4.0OUTPUT: 1 OUTPUT: 32
OUTPUT: 8
x = 15
y=2
print(x // y) #the floor division // rounds the result down to the nearest whole
number
11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
Management
38
Python Assignment Operators

 Assignment operators are used to assign values to variables:

Shri Madhwa Vadiraja Institute of Technology and


11/07/2025
Management
39

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
40
^

int(6 ^ 3) #The ^ operator compares each bit and set it to 1 if only one is 1,
otherwise (if both are 1 or both are 0) it is set to 0:
6 = 0000000000000110
3 = 0000000000000011 3 = 0000000000000011
4 = 0000000000000100
--------------------
5 = 0000000000000101
5 = 0000000000000101 6 = 0000000000000110
==================== 7 = 0000000000000111
Decimal numbers and their binary values:
0 = 0000000000000000
1 = 0000000000000001 OUTPUT:5

2 =Shri
0000000000000010
Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
41
Python Comparison Operators

 Comparison operators are used to compare two values:

11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
Management
42
Python Logical Operators

 Logical operators are used to combine conditional statements:

Shri Madhwa Vadiraja Institute of Technology and


11/07/2025
43
Python Identity Operators

 Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:

Shri Madhwa Vadiraja Institute of Technology and 11/07/2025


Management
44

IS
x = ["apple", "banana"] OUTPUT:
y = ["apple", "banana"] True
False
z=x True
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

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
45
IS NOT

x = ["apple", "banana"] OUTPUT


y = ["apple", "banana"] :
False
z=x True
print(x is not z) # returns False because z is the same object
Falseas 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.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
Python Membership Operators 46
The in and not in Operators

 Membership operators are used to test if a sequence is presented in an


object:

Shri Madhwa Vadiraja Institute of Technology and


11/07/2025
Management
47
in & not in

in:
x = ["apple", "banana"]
print("banana" in x) # returns True because a sequence with the value "banana" is in the list

not in:
x = ["apple", "banana"]
print("pineapple" not in x) # returns True because a sequence with the value "pineapple"
is not in the list
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
48

 You 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.
 These expressions will evaluate to a Boolean value.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
49

>>> ‘hello' in ['hello', 'hi', ‘hello', 'hey']


True
>>> spam = ['hello', 'hi', 'how', 'hey']
>>> 'cat' in spam
False
>>> ‘hello' not in spam
False
>>> 'cat' not in spam
True
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
50

 For example, 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.
myPets = [‘Rubi’, ‘Dooby’, ‘Tinku']
print('Enter a pet name:') The output may look something like this:
name = input()
Enter a pet name:
if name not in myPets:
Minku
print('I do not have a pet named ' + name)
I do not have a pet named Minku
else:
print(name + ' is my pet.')
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
51
Python Bitwise Operators

 Bitwise operators are used to compare (binary) numbers:

11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
52
Operator Precedence

 Operator precedence describes the order in which operations are


performed.

Parentheses has the highest precedence, meaning that expressions


inside parentheses must be evaluated first:

print((6 + 3) - (6 + 3))

OUTPUT: 0
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
53

Multiplication * has higher precedence than addition +, and therefor


multiplications are evaluated before additions:

print(100 + 5 * 3)

OUTPUT:
115
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
54
The precedence order is described in the table below,
starting with the highest precedence at the top:

Shri Madhwa Vadiraja Institute of Technology and


Management 11/07/2025
55

Shri Madhwa Vadiraja Institute of Technology and


11/07/2025
Management
56
If two operators have the same precedence, the
expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefor we


evaluate the expression from left to right:

print(5 + 4 - 7 + 3)

Output:5

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
57
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.
 So instead of doing this:

you could type this line of code:


cat = ['fat', 'black', 'loud']
size = cat[0] cat = ['fat', 'black', 'loud']
size, color, disposition = cat
color = cat[1]
disposition = cat[2]
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
58

The number of variables and the length of the list must be


exactly equal, or Python will give you a Value Error:-

cat = ['fat', 'black', 'loud']


size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
size, color, disposition, name = cat
ValueError: need more than 3 values to unpack
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
59
Augmented Assignment
operators
 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:
As a shortcut, you can use the augmented assignment
operator += to do
spam = 42 the same thing:
spam = spam + 1 >>> spam = 42
>>> spam >>> spam += 1
43 >>> spam
43
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
There are augmented assignment 60
operators for the +, -, *, /, and %
operators,

The += operator can also do string and list concatenation, and the *= operator
can do string and list replication.
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
61
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: [Link]('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.
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
Python has a set of built-in methods that
62
you can use on lists.

Shri Madhwa Vadiraja Institute of Technology and 11/07/2025


63
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.

Syntax: [Link](elmnt)

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
64
What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']


OUTPUT:2
x = [Link]("cherry")
>>> spam = ['hello', 'hi', ‘bye', ‘yes']
>>> [Link]('hello’)
0 >>> [Link](‘yes’)
3
>>> [Link](‘bye bye bye')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
[Link]('howdy howdy howdy')
ValueError: ‘bye bye bye' is not in list
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
65

When there are duplicates of the value in the list, the index of its first
appearance is returned. Enter the following into the interactive shell, and
notice that index() returns 1, not 3:

>>> spam = ['Zophie’, ‘zara', 'Fat-tail', ‘zara']


>>> [Link](‘zara')
1

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
66
Adding Values to Lists with the append()
and insert() Methods

 append() Method:
The append() method appends an element to the end of the list.

Syntax:
[Link](elmnt)
Parameter Description
elmnt Required. An element of any type (string, number,
object etc.)
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
67
Add an element to
the fruits list:

fruits = ['apple', 'banana', 'cherry']


[Link]("orange")
OUTPUT:['apple', 'banana', 'cherry', 'orange

a = ["apple", "banana", "cherry"]


b = ["Ford", "BMW", "Volvo"]
[Link](b)
print(a) OUTPUT:
['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
68
Insert() Method

Insert the value "orange" as the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
[Link](1, "orange") OUTPUT:
print(fruits) ['apple', 'orange', 'banana', 'cherry']

The insert() method inserts the specified value at the specified position.

Syntax pos Required. A number


specifying in which position
[Link](pos, elmnt) to insert the value
Shri Madhwa Vadiraja Institute of Technology and elmnt Required. An element of any
Management 11/07/2025
Add new values to a list, use the append() and insert() methods.69
Enter the following into the interactive shell to call the append() method on a list
value stored in the variable spam:

>>> spam = ['cat', 'dog', 'bat']


>>> [Link]('moose’)
The append() method call adds the argument
to the end of the list.
>>> spam
['cat', 'dog', 'bat', 'moose']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
70

 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.
 Enter the following into the interactive shell:

>>> spam = ['cat', 'dog', 'bat']


>>> [Link](1, ‘rat')
>>> spam
['cat', ‘rat', 'dog', 'bat'] 11/07/2025
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
71

Notice that the code is [Link]('moose') and [Link](1, ‘rat’), not spam =
[Link]('moose') and spam = [Link](1, ‘rat’).

Neither append() nor insert() gives the new value of spam as its return value.
(In fact, the return value of append() and insert() is None, so you definitely wouldn’t
want to store this as the new variable value.) Rather, the list is modified in place.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
72

 Methods belong to a single data type. 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.
 Enter the following into the interactive shell, and note the AttributeError error messages:

say = 'hello’ number = 42


[Link]('world’) [Link](1, 'world’)

Traceback (most recent call last):


Traceback (most recent call last): File "<pyshell#22>", line 1, in <module>
File "<pyshell#19>", line 1, in <module> [Link](1, 'world')
[Link]('world') AttributeError: 'int' object has no attribute 'insert'
AttributeError: 'str' object has no attribute 'append'
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
73
Removing Values from Lists with remove()

The remove() method removes the first occurrence of the element with the
specified value.
Syntax: Paramet Description
er
[Link](elmnt) elmnt Required. Any type (string, number, list
etc.) The element you want to remove
Remove the “pen" element of the fruit list:

fruits = ['apple', ’pen', 'cherry']


OUTPUT:
[Link](“pen")
['apple', 'cherry']
print(fruits)
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
74
The remove() method is passed the value to be removed from the
list it is called on. Enter the following into the interactive shell:

 The remove() method is passed the value to be removed from the list it is called
on. Enter the following into the interactive shell:

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> [Link]('bat')
>>> spam
['cat', 'rat', 'elephant']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
75

 Attempting to delete a value that does not exist in the list will result in a
ValueError error.
 For example, enter the following into the interactive shell and notice the error that
is displayed:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> [Link](‘chocolate’)

Traceback (most recent call last):


File "<pyshell#11>", line 1, in <module>
[Link](‘chocolate')
ValueError: [Link](x): x not in list
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
If the value appears multiple times in the list, only the first 76
instance of the value will be removed. Enter the following into the
interactive shell:

>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']


>>> [Link]('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', 'cat']

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.
Shri Madhwa Vadiraja Institute of Technology and
Management 11/07/2025
77
Sorting the Values in a List with the sort() Method

The sort() method sorts the list ascending by default.


You can also make a function to decide the sorting criteria(s).

Syntax:
[Link](reverse=True|False, key=myFunc)
Parameter Description
reverse Optional. reverse=True will sort the list descending. Default
is reverse=False

key Optional. A function to specify the sorting criteria(s)


Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
78
Sort the list descending:

You can also pass True for the reverse keyword argument to have sort()
sort the values in reverse order. Enter the following into the interactive shell:
cars = ['Ford', 'BMW', 'Volvo'] OUTPUT:
[Link](reverse=True) ['Volvo', 'Ford', 'BMW']
print(cars)

>>>spam = ['ants', 'cats', 'dogs', ‘tigers', 'elephants']


>>> [Link](reverse=True)
>>> spam
[‘tigers', ‘elephants', ‘dogs’, ‘cats', ‘ants']
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
79
Lists of number values or lists of strings can be sorted with the sort()
method. For example, enter the following into the interactive shell:

>>> spam = [2, 5, 3.14, 1, -7]


>>> [Link]()
>>> spam >>>spam = ['ants', 'cats', 'dogs', ‘bulls', 'elephants']
>>> [Link]()
[-7, 1, 2, 3.14, 5]
>>> spam
['ants', ‘bulls', 'cats', 'dogs', 'elephants']

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
There are three things you 80
should note about the sort()
method
 First, the sort() method sorts the list in place.
 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']
>>> [Link]()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
[Link]()
TypeError: unorderable types: str() < int()
Shri Madhwa Vadiraja Institute of Technology and
Management 11/07/2025
81

 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.
 For an example, enter the following into the interactive shell:

>>> spam = ['Alice', 'ants', 'Bob', ‘bat', 'Carol', 'cats']


>>> [Link]()
>>> spam

['Alice', 'Bob', 'Carol', 'ants', ‘bat', 'cats']


Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
82
If you need to sort the values in regular alphabetical order,
pass [Link] for the key keyword argument in the sort()
method call
spam = ['a', 'z', 'A', 'Z']
>>> [Link](key=[Link])
>>> 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.
Shri Madhwa Vadiraja Institute of Technology and
Management 11/07/2025
83
example Program: magic 8 Ball with
a list
 Instead of several lines of nearly identical elif statements, you can create a single
list that the code works with.
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[[Link](0,
len(messages) - 1)])
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
84

 Notice the expression you use as the index into messages:


[Link](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.
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
85
list-like types: Strings and
tuples

 Lists aren’t the only data types that represent ordered sequences of values.

 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.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
86

>>> name = 'Zophie'


>>> name[-2] >>> for i in name:
>>> name[0] 'i' print('* * * ' + i + ' * * *')
'Z’
OUTPUT:
>>> name[0:4]
>>> 'z' in name 'Zoph'
***Z***
***o***
False
***p***
>>> 'Zo' in name
True
***h***
>>> 'p' not in name ***i***
False
Shri Madhwa Vadiraja Institute of Technology and
***e*** 11/07/2025
Management
87
Mutable and Immutable Data
Types

 lists and strings are different in an important way.

 list value is a mutable data type: It can have values added, removed, or changed.

 However, a string is immutable: It cannot be changed.

 Trying to reassign a single character in a string results in a TypeError error.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
88

>>> name = 'Zophie a cat'

>>> name[7] = 'the'

Traceback (most recent call last):

File "<pyshell#50>", line 1, in <module>

name[7] = 'the'

TypeError: 'str' object does not support item assignment


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
89

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.
>>> name = 'Zophie a cat'
>>> newName = name[0:7] + 'the' + name[8:12]

>>> name We used [0:7] and [8:12] to refer to the characters that we don’t
'Zophie a cat' wish to replace.

>>> newName Notice that the original 'Zophie a cat' string is not modified
'Zophie the cat' because strings are immutable.
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
90
Although a list value is mutable, the second line in the following code
does not modify the list class:

>>> class = [1, 2, 3]


>>> class = [4, 5, 6]
>>> class
[4, 5, 6]

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]).
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
91

If you wanted to actually modify the original list in class to contain [4, 5, 6], you
would have to do something like this:
>>> class = [1, 2, 3]
>>> del class[2]
>>> del class[1]
>>> del class[0]
>>> [Link](4)
>>> [Link](5)
>>> [Link](6)
>>> class
[4, 5, 6]
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
92
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, ( and ), instead of square brackets, [ and ].
 Tuples are used to store multiple items in a single variable.
 A tuple is a collection which is ordered and unchangeable.

mytuple = ("apple", "banana", "cherry")

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
93
Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.


Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
94

>>> a = ('hello', 42, 0.5)


>>> a[0]
'hello'
>>> a[1:3]
(42, 0.5)
>>> len(a)
3

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
95

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.

>>> value = ('hello', 42, 0.5)


>>> value[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
value[1] = 99
TypeError: 'tuple' object does not support item assignment
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
96

 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. (Unlike some other
programming languages, in Python it’s fine to have a trailing comma after the last item in
a list or tuple.)
>>> type(('hello',))
<class 'tuple’>
>>> type(('hello’))
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
<class 'str'> 11/07/2025
97

 You can use tuples to convey to anyone reading your code that you don’t intend
for that sequence of values to change.
 If you need an ordered sequence of values that never changes, use a tuple.
 A second benefit of using tuples instead of lists is that, because they are
immutable and their contents don’t change, Python can implement some
optimizations that make code using tuples slightly faster than code using lists.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
98
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:

>>> tuple(['cat', 'dog', 5]) >>> list('hello’) >>> list(('cat', 'dog', 5))
['h', 'e', 'l', 'l', 'o'] ['cat', 'dog', 5]
('cat', 'dog', 5)
Converting a tuple to a list is handy if you need a mutable version of a tuple value.
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
Management
99
References

 As you’ve seen, variables store strings and integer values.

>>> spam = 42 You assign 42 to the spam variable, and then you copy the
>>> cheese = spam value in spam and assign it to the variable cheese.
>>> spam = 100
>>> spam When you later change the value in spam to 100, this
100 doesn’t affect the value in cheese.
>>> cheese
42 This is because spam and cheese are different variables
that store different values.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
 But lists don’t work this way. When you assign a list to a variable, you are 10
actually assigning a list reference to the variable. A reference is a value that0
points to some bit of data, and a list reference is a value that points to a list.

>>> spam = [0, 1, 2, 3, 4, 5] The code changed only the cheese list, but it seems that
>>> cheese = spam both the cheese and spam lists have changed.
>>> cheese[1] = 'Hello!'
When you create the list, you assign a reference to it in
>>> spam
the spam variable.
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese But the next line copies only the list reference in spam to
[0, 'Hello!', 2, 3, 4, 5] cheese, not the list value itself. This means the values
stored in spam and cheese now both refer to the same list.

So when you modify the first element of cheese you are


modifying the same list that spam refers to.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
10
1

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
10
2

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
10
3

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
10
4

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.

Although Python variables technically contain references to list or dictionary values, people
often casually say that the variable contains the list or dictionary.
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
10
5
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.
 This means a copy of the reference is used for the parameter.
def fname(someParameter):
Notice that when fname() is called, a return value is not
[Link]('Hello')
used to assign a new value to spam. Instead, it modifies
spam = [1, 2, 3]
the list in place, directly. When run, this program
fname(spam)
output: produces the following :
print(spam)
[1, 2, 3, 'Hello']
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
10
6

 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.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
10
7
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.

 The first of these, [Link](), can be used to make a duplicate copy of a mutable
value like a list or dictionary, not just a copy of a reference.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
10
8

>>> import copy


Now the spam and cheese variables refer to
>>> spam = ['A', 'B', 'C', 'D'] separate lists, which is why only the list in
>>> cheese = [Link](spam) cheese is modified when you assign 42.
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
As you can see in 10
Figure 4-7, the reference ID numbers are no longer the same9for
both variables because the variables refer to independent lists.

Shri Madhwa Vadiraja Institute of Technology and 11/07/2025


Management
11
0

 If the list you need to copy contains lists, then use the
[Link]() function instead of [Link]().
 The deepcopy() function will copy these inner lists as well.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
5 11
1
DiCtionArieS AnD
StruCturingDAtA
 The dictionary data type:
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection of values which is ordered*, changeable and do not allow
duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Create and print a dictionary: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
OUTPUT: }
{'brand': 'Ford', 'model': 'Mustang', 'year': print(thisdict) 11/07/2025
1964}
Shri Madhwa Vadiraja Institute of Technology and
11
Dictionary Items 2

 Dictionary items are ordered, changeable, and does not allow duplicates.
 Dictionary items are presented in key:value pairs, and can be referred to by using
the key name.
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang", Output:
"year": 1964 Ford
}
print(thisdict["brand"])
Shri Madhwa Vadiraja Institute of Technology and 11/07/2025
Management
Ordered or Unordered?
11
Changeable 3

 When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
 Unordered means that the items does not have a defined order, you cannot refer to
an item by using an index.

Changeable
 Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
11
Duplicates Not Allowed 4

Dictionaries cannot have two items with the same key:

Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang", Output:
"year": 1964, {'brand': 'Ford', 'model': 'Mustang',
"year": 2020 'year': 2020}
}
print(thisdict)
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
11
5
Dictionaries vs. Lists

 Unlike lists, items in dictionaries are unordered.


 The first item in a list named spam would be spam[0]. But there is no “first”
item in a dictionary.
 While the order of items matters for determining whether two lists are the same,
it does not matter in what order the key-value pairs are typed in a dictionary.
Enter the following into the interactive shell:

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
11
6

>>> a = ['cats', 'dogs', ‘rats']


>>> b = ['dogs', ‘rats', 'cats']
>>> a == b
False
>>> a = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> b = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> a == b
True
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
11
7

 Because dictionaries are not ordered, they can’t be sliced like lists.
 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.
 Enter the following into the interactive shell, and notice the error message that shows up
because there is no 'color' key:
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
spam['color']
KeyError: 'color'
11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
11
8

 Though dictionaries are not ordered, the fact that you can have arbitrary values for
the keys allows you to organize your data in powerful ways.
 Say you wanted your program to store data about your friends’ birthdays.
 You can use a dictionary with the names as keys and the birthdays as values.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
11
9

birthdays = {'Alice': 'Apr 1', 'Bob':


'Dec 12', 'Carol': 'Mar 4'} else:
while True: print('I do not have birthday information for
print('Enter a name: (blank to quit)') ' + name)
name = input() print('What is their birthday?')
if name == '': bday = input()
break birthdays[name] = bday
if name in birthdays: print('Birthday database updated.’)
print(birthdays[name] + ' is the Print(birthdays)
birthday of ' + name)
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
0

You create an initial dictionary and store it in birthdays.


You can see if the entered name exists as a key in the dictionary with the in keyword,
just as you did for lists.
If the name is in the dictionary, you access the associated value using square brackets;
if not, you can add it using the same square bracket syntax combined with the
assignment operator.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
12
1

Enter a name: (blank to quit)


Alice
Apr 1 is the birthday of Alice birthdays = {'Alice': 'Apr 1', 'Bob':
Enter a name: (blank to quit) 'Dec 12', 'Carol': 'Mar
Preethi 4’,’Preethi’:’Feb 4’}
I do not have birthday information for Preethi Enter a name: (blank to quit)
What is their birthday?
Feb 4
Birthday database updated.
Enter a name: (blank to quit)
Preethi
Feb 4 is the birthday of Preethi
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
The keys(), values(), and items() 2
Methods

 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().

 The values returned by these methods are not true lists: They cannot be

modified and do not have an append() method. But these data types (dict_keys,
dict_values, and dict_items, respectively) can be used in for loops.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
3

>>> spam = {'color': 'red', 'age': 42}


>>> for v in [Link]():
print(v)
OUTPUT:
red
42

Here, a for loop iterates over each of the values in the spam dictionary.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
12
A for loop can also iterate over the keys or both keys
4
and values:

spam = {'color': 'red', 'age': 42}


for k in [Link](): for i in [Link]():
print(k)
print(i)

Output:
Output:
color
age ('color', 'red')
('age', 42) 11/07/2025
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
12
5

 Using the keys(), values(), and items() methods, a for loop can iterate
over the keys, values, or key-value pairs in a dictionary, respectively.
 Notice that the values in the dict_items value returned by the items()
method are tuples of the key and value.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
12
6

 If you want a true list from one of these methods, pass its list-like return
value to the list() function.

>>> spam = {'color': 'red', 'age': 42}


>>> [Link]()
dict_keys(['color', 'age']) The list([Link]()) line takes the dict_keys value

>>> list([Link]()) returned from keys() and passes it to list(), which

['color', 'age'] then returns a list value of ['color', 'age'].


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
7

 You can also use the multiple assignment trick in a for loop to assign the key
and value to separate variables

>>> spam = {'color': 'red', 'age': 42}


>>> for k, v in [Link]():
print('Key: ' + k + ' Value: ' + str(v))

Key: color Value: red


Key: age Value: 42
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
12
Checking Whether a Key or 8
Value Exists in a Dictionary
 The in and not in operators can check whether a value exists in a list. You can
also use these operators to see whether a certain key or value exists in a
dictionary. >>> 'color' in [Link]()
False
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'color' not in [Link]()
>>> 'name' in [Link]() True
True
>>> 'color' in spam
>>> 'Zophie' in [Link]() False
True
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
11/07/2025
12
9
The get() Method

 It’s tedious to check whether a key exists in a dictionary before accessing that key’s value.
Fortunately, dictionaries have a get() method that takes two arguments: the key of the
value to retrieve and a fallback value to return if that key does not exist.
>>> picnicItems = {'apples': 5, ‘chocolates': 2}
>>> 'I am bringing ' + str([Link](‘chocolates', 0)) + ‘ chocolates.'
'I am bringing 2 chocolates.'
>>> 'I am bringing ' + str([Link](‘fans', 0)) + ‘ fans.'
'I am bringing 0 fans.
Because there is no ‘fans' key in the picnicItems dictionary, the default 11/07/2025
Shri Madhwa Vadiraja Institute of Technology and Manage
value
ment 0 is returned by the get() method.
13
0

 Without using get(), the code would have caused an error message, such as
in the following example:

>>> picnicItems = {'apples': 5, 'cups': 2}


>>> 'I am bringing ' + str(picnicItems[‘fans']) + ‘ fans.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems[‘fans']) + ‘ fans.'
KeyError: ‘fans'

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
13
1
The setdefault() Method

 You’lloften have to set a value in a dictionary for a certain key only if that
key does not already have a value.

spam = {'name': ‘Pooja', 'age': 5}


if 'color' not in spam:
spam['color'] = 'black’
print(spam)

{'name': ‘Pooja', 'age': 5, 'color': 'black'}


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
13
2

>>> spam = {'name': ‘Pooja', 'age': 5}


 The setdefault() method offers a way to >>> [Link]('color', 'black')
do this in one line of code. 'black’
 The first argument passed to the >>> spam
method is the key to check for, and the {'name': 'Pooja', 'age': 5, 'color': 'black'}
second argument is the value to set at
that key if the key does not exist. >>> [Link]('color', 'white')
 If the key does exist, the setdefault() 'black’
method returns the key’s value.
>>> spam
Shri Madhwa Vadiraja Institute of Technology and Manage
ment
{'name': 'Pooja', 'age': 5, 'color': 'black'}
11/07/2025
13
3

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
13
4

 The first time setdefault() is called, the dictionary in spam changes to {'name':
'Pooja', 'age': 5, 'color': 'black'}. The method returns the value 'black' because
this is now the value set for the key 'color’.

 When [Link]('color', 'white') is called next, the value for that key is not
changed to 'white' because spam already has a key named 'color’.

 The setdefault() method is a nice shortcut to ensure that a key exists.


Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
13
Here is a short program that counts the number of 5
occurrences of each letter in a string

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
print(count)
{' ': 13,',': 1,'.': 1,'A': 1,'I': 1,'a': 4,'b': 1,'c': 3,'d': 3,'e': 5,'g': 2,'h': 3,'i': 6,
'k': 2,'l': 3,'n': 4,'o': 2,'p': 1,'r': 5,'s': 3,'t': 6,'w': 2,'y': 1}
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
13
6

 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.
{' ': 13,',': 1,'.': 1,'A': 1,'I': 1,'a': 4,'b': 1,'c': 3,'d': 3,'e': 5,'g': 2,'h': 3,'i': 6,
'k': 2,'l': 3,'n': 4,'o': 2,'p': 1,'r': 5,'s': 3,'t': 6,'w': 2,'y': 1}

From the output, you can see that the lowercase letter c appears 3 times, the space character appears 13 times,
and the uppercase letter A appears 1 time. This program will work no matter what string is inside the message
variable, even
Shri Madhwa if theInstitute
Vadiraja stringofis millions
Technology andof characters long!
Manage 11/07/2025
ment
13
7
Pretty Printing

 If you import the pprint module into your programs, you’ll have access to the
pprint() and pformat() functions that will “pretty print” a dictionary’s values.
 This is helpful when you want a cleaner display of the items in a dictionary than
what print() provides.
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
[Link](count)
11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
Management
This time, when the program is run, the
13
8
output looks much cleaner, with the
keys
{' ': 13,
sorted
',': 1, 'k': 2,
'.': 1, 'l': 3,
'A': 1, 'n': 4,
'I': 1, 'o': 2, The [Link]() function is especially helpful when the
'a': 4, 'p': 1, dictionary itself contains nested lists or dictionaries.
'b': 1, 'r': 5,
'c': 3, 's': 3,
'd': 3, 't': 6,
'e': 5, 'w': 2,
'g': 2, 'y': 1}
'h': 3,
'i': 6,
Shri Madhwa Vadiraja Institute of Technology and
11/07/2025
13
9

 If you want to obtain the prettified text as a string value instead of displaying it on
the screen, call [Link]() instead.
 These two lines are equivalent to each other:

[Link](someDictionaryValue)
print([Link](someDictionaryValue))

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
14
0
Nested Dictionaries and Lists

 As you model more complicated things, you may find you need dictionaries and
lists that contain other dictionaries and lists.
 Lists are useful to contain an ordered series of values, and dictionaries are useful
for associating keys with values.
 Forexample, here’s a program that uses a dictionary that contains other
dictionaries in order to see who is bringing what to a picnic.

The totalBrought() function can read this data structure and calculate the
total number of an item being brought by all the guests.
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
14
1

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
14
2

 Inside the totalBrought() function, the for loop iterates over the key-value 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.

Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025


ment
The output of this program looks like14
3
this:

Number of things being brought:


This may seem like such a simple thing to
- Apples 7 model that you wouldn’t need to bother with
- Cups 3 writing a program to do it.
- Cakes 0 But realize that this same totalBrought()
- Ham Sandwiches 3 function could easily handle a dictionary that
- Apple Pies 1 contains thousands of guests, each bringing
thousands of different picnic items.
Then having this information in a data structure
along with the totalBrought() function would
save you a lot of time!
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment

You might also like