Understanding Python Lists and Usage
Understanding Python Lists and Usage
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 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:
OUTPUT:
['apple', 'banana', 'cherry']
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:
Output:3
From Python's perspective, lists are defined as objects with the data type 'list':
<class '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
print(thislist) OUTPUT:
List
items are indexed and you can access them by referring to the index
number:
-1 refers to the last item, -2 refers to the second last item etc.
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
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[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":
print(thislist[:4])
OUTPUT:
['apple', 'banana', 'cherry', 'orange']
Example
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
Example
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:
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:
Example
Change the second and third value by replacing it with one value:
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:
OUTPUT:
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
31
For loop repeats the code block once for each value in a list or list-like value.
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
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
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
11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
Management
42
Python Logical 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:
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
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.
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
11/07/2025
Shri Madhwa Vadiraja Institute of Technology and
52
Operator Precedence
print((6 + 3) - (6 + 3))
OUTPUT: 0
Shri Madhwa Vadiraja Institute of Technology and Manage 11/07/2025
ment
53
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:
print(5 + 4 - 7 + 3)
Output:5
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 += 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
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 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.
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)
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:
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:
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.
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:
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.
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:
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:
The remove() method is passed the value to be removed from the list it is called
on. Enter the following into the interactive shell:
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’)
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
Syntax:
[Link](reverse=True|False, key=myFunc)
Parameter Description
reverse Optional. reverse=True will sort the list descending. Default
is reverse=False
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)
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:
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
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
list value is a mutable data type: It can have values added, removed, or changed.
name[7] = 'the'
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:
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.
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
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. (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.
>>> 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
>>> 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.
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.
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
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.
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.
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
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.
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
Here, a for loop iterates over each of the values in the spam dictionary.
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.
If you want a true list from one of these methods, pass its list-like return
value to the list() function.
You can also use the multiple assignment trick in a for loop to assign the key
and value to separate variables
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:
You’lloften have to set a value in a dictionary for a certain key only if that
key does not already have a value.
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’.
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))
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
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.