0% found this document useful (0 votes)
25 views

Module 2

Uploaded by

Tanvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Module 2

Uploaded by

Tanvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Python Programming-21EC643

Module 2

Lists, Tuples and Dictionaries

Data Structures: Lists: The List Data Type, Working with Lists Strings: Manipulating Strings,
Working with Strings, Useful String Methods Tuples and Dictionaries, basics Using Data
Structures to Model Real-World Things, Manipulating Strings.

The List Data Type

 A list in Python is a collection of ordered items, which can be of any data


type, such as numbers, strings, or other objects. Lists are written in square
brackets, with items separated by commas. For example:
numbers = [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry"]
 The data type list is an ordered sequence which is mutable and made up of
one or more elements.
 Unlike a string which consists of only characters, a list can have elements of
different data types, such as integer, float, string, tuple or even another list.
 A list is very useful to group together elements of mixed data types.
 Elements of a list are enclosed in square brackets and are separated by
comma. Like string indices, list indices also start from 0.
 A list begins with an opening square bracket and ends with a closing square
bracket, [ ].
 Values inside the list are also called items.
 Items are separated with commas (that is, they are comma-delimited).
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
#list2 is the list of vowels
>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']

Nisha S K, Assistant Professor, SVIT Page 1


Python Programming-21EC643

>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested list
>>> list4 =[['Physics',101],['Chemistry',202], ['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202], ['Maths', 303]]

Getting Individual Values in a List with Indexes (Accessing Elements in


a List)

 Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam.
 The Python code spam[0] would evaluate to 'cat', and 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.

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


>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat‘
>>> spam=[1,2,3,4,5]
>>> spam[4]
5
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant‘
>>> 'Hello, ' + spam[0]
'Hello, cat’

Nisha S K, Assistant Professor, SVIT Page 2


Python Programming-21EC643

>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.‘
'The bat ate the cat.'
>>> spam=[1,2,3,4,5]
>>> 'I ate',spam[1],'Dosas today.‘
('I ate', 2, 'Dosas today.')
>>> 'I ate'+spam[1]+'Dosas today.’
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError:
can only concatenate str (not "int") to str
>>> 'I ate '+str(spam[1])+' Dosas today.‘
'I ate 2 Dosas today.'
Python will give you an IndexError error message if you use an index
that exceeds the number of values in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
 Indexes can be only integer values, not floats. The following example
will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
 Lists can also contain other list values. The values in these lists of lists
can be accessed
Using multiple indexes, like so:
>>> spam=[['Hi','Hello'],[‘Will',‘Dave',‘Tom',‘Chris']]
>>> spam[0]

Nisha S K, Assistant Professor, SVIT Page 3


Python Programming-21EC643

['Hi', 'Hello']
>>> spam[1]
[‘Will',‘Dave',‘Tom',‘Chris']
>>> spam[0][1]
'Hello’
>>> spam[1][2]
'Tom‘
>>> 'I want to tell '+str(spam[0][0])+' '+str(spam[1][0])
'I want to tell Hi Will'

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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'

Lists are Mutable

 In Python, lists are mutable.


 It means that the contents of the list can be changed after it has been
created.
#List list1 of colors
>>> list1 = ['Red','Green','Blue','Orange']
#change/override the fourth element of list1
>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

Nisha S K, Assistant Professor, SVIT Page 4


Python Programming-21EC643

Getting a List from another List with Slices

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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
#list1 is truncated to the end of the list
>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[7:2] #first index > second index
[ ] #results in an empty list
#return sublist from index 0 to 4
>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']

Nisha S K, Assistant Professor, SVIT Page 5


Python Programming-21EC643

#slicing with a given step size


>>> list1[0:6:2]
['Red','Blue','Magenta']
#negative indexes
#elements at index -6,-5,-4,-3 are sliced
>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta']
#both first and last index missing
>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']
#negative step size
#whole list in the reverse order
>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']

Getting a List’s Length with the len() Function


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.
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3

Changing Values in a List with Indexes


 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'.”
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]

Nisha S K, Assistant Professor, SVIT Page 6


Python Programming-21EC643

>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]

List Concatenation and List Replication


 Lists can be concatenated and replicated just like strings.
 The + operator combines two lists to create a new list value and
the * operator can be used with a list and an integer value to replicate the
list.
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']

Removing Values from Lists with del Statements


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]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

Traversing a List

We can access each element of the list or traverse a list using a for loop or a
while loop.

Nisha S K, Assistant Professor, SVIT Page 7


Python Programming-21EC643

(A) List Traversal Using for Loop:


>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black

Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black

(B) List Traversal Using while Loop:

>>> list1 = ['Red','Green','Blue','Yellow', 'Black']


>>> i = 0
>>> while i < len(list1):
print(list1[i]) i += 1
Output:
Red
Green
Blue
Yellow
Black

Nisha S K, Assistant Professor, SVIT Page 8


Python Programming-21EC643

Working with Lists

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)

Output:
Enter the name of cat 1 (Or enter nothing to stop.):
Pooka
Enter the name of cat 2 (Or enter nothing to stop.):
eer
Enter the name of cat 3 (Or enter nothing to stop.):

The cat names are:


Pooka
Eer

The in and not in Operators (Membership)


 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.
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False

Nisha S K, Assistant Professor, SVIT Page 9


Python Programming-21EC643

>>> 'cat' not in spam


True

Example:

myPets = ['Zophie', 'Pooka', 'Fat-tail']


print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

Output:

Enter a pet name:


Err
I do not have a pet named Err

The Multiple Assignment Trick


 The multiple assignment trick (technically called tuple unpacking) 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:
>>> cat = ['fat', 'gray', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition = cat
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

Nisha S K, Assistant Professor, SVIT Page 10


Python Programming-21EC643

Using the enumerate() Function with Lists

 Instead of using the range(len(someList)) technique with a for loop to


obtain the integer index of the items in the list, you can call
the enumerate() function instead. On each iteration of the
loop, enumerate() will return two values: the index of the item in the list, and
the item in the list itself.
>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
>>> for index, item in enumerate(supplies):
... print('Index ' + str(index) + ' in supplies is: ' + item)

Index 0 in supplies is: pens


Index 1 in supplies is: staplers
Index 2 in supplies is: flamethrowers
Index 3 in supplies is: binders

Using the random.choice() and random.shuffle() Functions with Lists

 The random module has a couple functions that accept lists for
arguments. The random.choice() function will return a randomly selected
item from the list.
>>> import random
>>> pets = ['Dog', 'Cat', 'Moose']
>>> random.choice(pets)
'Dog'
>>> random.choice(pets)
'Cat'
>>> random.choice(pets)
'Cat'
 The random.shuffle() function will reorder the items in a list. This function
modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)

Nisha S K, Assistant Professor, SVIT Page 11


Python Programming-21EC643

>>> people
['Alice', 'David', 'Bob', 'Carol']

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:

>>> spam = 42
>>> spam = spam + 1
>>> spam
43

As a shortcut, you can use the augmented assignment operator += to do the


same thing:

>>> spam = 42
>>> spam += 1
>>> spam
43

Nisha S K, Assistant Professor, SVIT Page 12


Python Programming-21EC643

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

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.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
 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', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1

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


 To add new values to a list, use the append() and insert() methods.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam

Nisha S K, Assistant Professor, SVIT Page 13


Python Programming-21EC643

['cat', 'dog', 'bat', 'moose']


 The previous append() method call adds the argument to the end of the
list. 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.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
 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.
>>> eggs = 'hello'
>>> eggs.append('world')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
eggs.append('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> bacon.insert(1, 'world')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'

Removing Values from Lists with the remove() Method

 The remove() method is passed the value to be removed from the list it is
called on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
 Attempting to delete a value that does not exist in the list will result in
a ValueError error.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')

Nisha S K, Assistant Professor, SVIT Page 14


Python Programming-21EC643

Traceback (most recent call last):


File "<pyshell#11>", line 1, in <module>
spam.remove('chicken')
ValueError: list.remove(x): x not in list
 If the value appears multiple times in the list, only the first instance of the
value will be removed.
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('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 useful when you
know the value you want to remove from the list.

Sorting the Values in a List with the sort() Method

 Lists of number values or lists of strings can be sorted with


the sort() method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
 You can also pass True for the reverse keyword argument to
have sort() sort the values in reverse order.
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
 There are three things you should note about the sort() method. First,
the sort() method sorts the list in place; don’t try to capture the return value
by writing code like spam = spam.sort().
 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.

Nisha S K, Assistant Professor, SVIT Page 15


Python Programming-21EC643

>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']


>>> spam.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
spam.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
 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)
>>> spam
['a', 'A', 'z', 'Z']

Reversing the Values in a List with the reverse() Method

 If you need to quickly reverse the order of the items in a list, you can call
the reverse() list method.
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']

Magic 8 Ball with a List

import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',

Nisha S K, Assistant Professor, SVIT Page 16


Python Programming-21EC643

'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)])

The above program gives us output randomly picking any string from the list.
The output changes whenever it is executed.

List Methods and Built-in Functions(Summary)

Method Description Example

>>> list1 = [10,20,30,40,50]


Returns the length of
len() the list passed as the >>> len(list1)
argument 5

>>> list1 = list()


Creates an empty list if
no argument is passed >>> list1
[]
list() >>> str1 = 'aeiou'
Creates a list if a >>> list1 = list(str1)
sequence is passed as
>>> list1
an argument
['a', 'e', 'i', 'o', 'u']
>>> list1 = [10,20,30,40]
Appends a single >>> list1.append(50)
element passed as an >>> list1
argument at the end of [10, 20, 30, 40, 50]
append()
the list. The single >>> list1 = [10,20,30,40]
element can also be a >>> list1.append([50,60])
list
>>> list1
[10, 20, 30, 40, [50, 60]]
Appends each element >>> list1 = [10,20,30]
extend()
of the list passed as >>> list2 = [40,50]

Nisha S K, Assistant Professor, SVIT Page 17


Python Programming-21EC643

argument to the end of >>> list1.extend(list2)


the given list >>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
Inserts an element at a >>> list1
insert() particular index in the [10, 20, 25, 30, 40, 50]
list >>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
>>> list1 =
Returns the number of [10,20,30,10,40,10]
count() times a given element >>> list1.count(10) 3
appears in the list >>> list1.count(90)
0
Returns index of the >>> list1 =
first occurrence of the [10,20,30,20,40,10]
element in the list. If
index() >>> list1.index(20) 1
the element is not
present, ValueError is >>> list1.index(90)
generated ValueError: 90 is not in list
Removes the given >>> list1 =
element from the list. [10,20,30,40,50,30]
If the element is >>> list1.remove(30)
present multiple times, >>> list1
only the first
remove() [10, 20, 40, 50, 30]
occurrence is removed.
If the element is not >>> list1.remove(90)
present, then ValueError:list.remove(x):x
ValueError is not in list
generated
Returns the element >>> list1 =
whose index is passed [10,20,30,40,50,60]
as parameter to this >>> list1.pop(3) 40
function and also >>> list1
pop() removes it from the
[10, 20, 30, 50, 60]
list. If no parameter is
given, then it returns >>> list1 =
and removes the last [10,20,30,40,50,60]
element of the list >>> list1.pop() 60
>>> list1

Nisha S K, Assistant Professor, SVIT Page 18


Python Programming-21EC643

[10, 20, 30, 40, 50]


>>> list1 =
[34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
Reverses the order of
>>> list1 = [ 'Tiger' ,'Zebra' ,
reverse() elements in the given
'Lion' , 'Cat' ,'Elephant'
list
,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat',
'Lion', 'Zebra', 'Tiger']
>>>list1 =
['Tiger','Zebra','Lion',
'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
Sorts the elements of ['Cat', 'Dog', 'Elephant',
sort()
the given list in-place 'Lion', 'Tiger', 'Zebra']
>>> list1 =
[34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
>>> list1 =
It takes a list as [23,45,11,67,85,56]
parameter and creates >>> list2 = sorted(list1)
a new list consisting of
sorted() >>> list1
the same elements
arranged in sorted [23, 45, 11, 67, 85, 56]
order >>> list2
[11, 23, 45, 56, 67, 85]
>>> list1 =
Returns minimum or [34,12,63,39,92,44]
min() smallest element of
the list >>> min(list1) 12

Returns maximum or
max() largest element of the >>> max(list1) 92
list

Nisha S K, Assistant Professor, SVIT Page 19


Python Programming-21EC643

Returns sum of the >>> sum(list1)


sum()
elements of the list
284

Sequence Data Types

 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.
 The Python sequence data types include lists, strings, range objects
returned by range(), and tuples.
 Many of the things you can do with lists can also be done with strings and
other values of sequence types: indexing; slicing; and using them
with for loops, with len(), and with the in and not in operators.
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *')

* * * Z***
* * * o***
* * * p***
* * * h***
* * * i***
* * * e***

Nisha S K, Assistant Professor, SVIT Page 20


Python Programming-21EC643

Mutable and Immutable Data Types

 A list value is a mutable data type: it can have values added, removed, or
changed. However, a string is immutable: it cannot be changed.
>>> 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
 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='My name Nisha'
>>> newname=name[0:7]+‘ is '+name[8:13]
‘My name is Nisha’
 Although a list value is mutable.
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[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])

 For modifying we use the method below.


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

Nisha S K, Assistant Professor, SVIT Page 21


Python Programming-21EC643

>>> del eggs[2]


>>> del eggs[1]
>>> del eggs[0]
>>> eggs.append(4)
>>> eggs.append(5)
>>> eggs.append(6)
>>> eggs
[4, 5, 6]

Nested Lists

 When a list appears as an element of another list, it is called a nested list.


>>> list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
 To access the element of the nested list of list1, we have to specify two
indices list1[i][j].
 The first index i will take us to the desired nested list and second index j
will take us to the desired element in that nested list.
>>> list1[4][1]
7

Nisha S K, Assistant Professor, SVIT Page 22


Python Programming-21EC643

Copying Lists:

 Given a list, the simplest way to make a copy of the list is to assign it to
another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
 The statement list2 = list1 does not create a new list.
 Rather, it just makes list1 and list2 refer to the same list object.
 Here list2 actually becomes an alias of list1.
 Therefore, any changes made to either of them will be reflected in the
other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
 We can also create a copy or clone of the list as a distinct object by three
methods.
 The first method uses slicing, the second method uses built-in function
list() and the third method uses copy() function of python library copy.
Method 1
 We can slice our original list and store it into a new variable as follows:
newList = oldList[:]
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2
We can use the built-in function list() as follows:
newList = list(oldList)

Nisha S K, Assistant Professor, SVIT Page 23


Python Programming-21EC643

>>> list1 = [10,20,30,40]


>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]
Method 3
We can use the copy () function as follows:
import copy #import the library copy
#use copy()function of library copy
newList = copy.copy(oldList)
Example
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2
[1, 2, 3, 4, 5]

Program to increment the elements of a list. The list is passed as an


argument to a function.

def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print('Reference of list Inside Function',id(list2))
list1 = [10,20,30,40,50] #Create a list
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)
Output:
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 140290458650304
The list after the function call
[15, 25, 35, 45, 55]

Nisha S K, Assistant Professor, SVIT Page 24


Python Programming-21EC643

Program to increment the elements of the list passed as parameter.

def increment(list2):
print("\nID of list inside function before assignment:",id(list2))
list2 = [15,25,35,45,55] #List2 assigned a new list
print("ID of list changes inside function after assignment:",id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)

Output:
ID of list before function call: 140642743551680
The list before function call:
[10, 20, 30, 40, 50]

ID of list inside function before assignment: 140642743551680


ID of list changes inside function after assignment: 140642742108608
The list inside the function after assignment is:
[15, 25, 35, 45, 55]

ID of list after function call: 140642743551680


The list after the function call:
[10, 20, 30, 40, 50]

List Manipulation:
Write a menu driven program to perform various list operations, such
as:
• Append an element
• Insert an element

Nisha S K, Assistant Professor, SVIT Page 25


Python Programming-21EC643

• Append a list to the given list


• Modify an existing element
• Delete an existing element from its position
• Delete an existing element with a given value
• Sort the list in ascending order
• Sort the list in descending order
• Display the list.

myList = [22,4,16,38,13]
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")

Nisha S K, Assistant Professor, SVIT Page 26


Python Programming-21EC643

elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()

Nisha S K, Assistant Professor, SVIT Page 27


Python Programming-21EC643

Output:

The list 'myList' has the following elements [22, 4, 16, 38, 13]

LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 7

The list has been sorted


The list 'myList' has the following elements [4, 13, 16, 22, 38]

LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 8

The list has been sorted in reverse order


The list 'myList' has the following elements [38, 22, 16, 13, 4]

LISTOPERATIONS
1. Append an element

Nisha S K, Assistant Professor, SVIT Page 28


Python Programming-21EC643

2. Insert an element at the desired position


3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 10

A program to calculate average marks of n students using a function


where n is entered by the user.

def computeAverage(list1,n):
total = 0
for marks in list1:
total = total + marks
average = total / n
return average
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)

Output:
How many students marks you want to enter:
5
Enter marks of student 1 :
45
Enter marks of student 2 :
89

Nisha S K, Assistant Professor, SVIT Page 29


Python Programming-21EC643

Enter marks of student 3 :


79
Enter marks of student 4 :
76
Enter marks of student 5 :
55
Average marks of 5 students is: 68.8

Write a user-defined function to check if a number is present in the list


or not. If the number is present, return the position of the number.
Print an appropriate message if the number is not present in the list.

def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")

Output:
How many numbers do you want to enter in the list:
5
Enter a list of numbers:
23
567
12

Nisha S K, Assistant Professor, SVIT Page 30


Python Programming-21EC643

89
324
Enter the number to be searched: 12
Number 12 is present at 3 position

The Tuple Data Type


 A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas.
 Like list and string, elements of a tuple can be accessed using index
values, starting from 0.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
 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.
 >>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
#tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
>>> tuple2 =('Economics',87,'Accountancy',89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
#tuple3 is the tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
(10, 20, 30, [40, 50])

Nisha S K, Assistant Professor, SVIT Page 31


Python Programming-21EC643

#tuple4 is the tuple with tuple as an element


>>> tuple4 = (1,2,3,4,5,(10,20))
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
 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, it’s fine to have a trailing comma after the last item in a list or
tuple in Python.)
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

Accessing Elements in a Tuple


 Elements of a tuple can be accessed in the same way as a list or string
using indexing and slicing.
>>> tuple1 = (2,4,6,8,10,12)
#initializes a tuple tuple1
#returns the first element of tuple1
>>> tuple1[0]
2
#returns fourth element of tuple1
>>> tuple1[3]
8
#returns error as index is out of range
>>> tuple1[15]
IndexError: tuple index out of range #an expression resulting in an
integer index
>>> tuple1[1+4]
12
#returns first element from right
>>> tuple1[-1]
12

Nisha S K, Assistant Professor, SVIT Page 32


Python Programming-21EC643

Tuple is Immutable
 Tuple is an immutable data type. It means that the elements of a tuple
cannot be changed after it has been created. An attempt to do this would
lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
 However an element of a tuple may be of mutable type, e.g., a list.
#4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple2
>>> tuple2[3][1] = 10
#modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])

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.
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Tuple Operations
Concatenation
Python allows us to join tuples using concatenation operator depicted
by symbol +. We can also create a new tuple which contains the result
of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)

>>> tuple2 = (2,4,6,8,10)

>>> tuple1 + tuple2 #concatenates two tuples

Nisha S K, Assistant Professor, SVIT Page 33


Python Programming-21EC643

(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

>>> tuple3 = ('Red','Green','Blue')

>>> tuple4 = ('Cyan', 'Magenta', 'Yellow'

,'Black')

#tuple5 stores elements of tuple3 and tuple4

>>> tuple5 = tuple3 + tuple4

>>> tuple5 ('Red','Green','Blue','Cyan','Magenta', 'Yellow','Black')

Concatenation operator can also be used for extending an existing


tuple. When we extend a tuple using concatenation a new tuple is
created.
>>> tuple6 = (1,2,3,4,5)

#single element is appended to tuple6

>>> tuple6 = tuple6 + (6,)

>>> tuple6

(1, 2, 3, 4, 5, 6)

#more than one elements are appended

>>> tuple6 = tuple6 + (7,8,9)

>>> tuple6

(1, 2, 3, 4, 5, 6, 7, 8, 9)

Repetition
Repetition operation is depicted by the symbol *. It is used to repeat
elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand
to be an integer only.
>>> tuple1 = ('Hello','World')

>>> tuple1 * 3

('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Nisha S K, Assistant Professor, SVIT Page 34


Python Programming-21EC643

#tuple with single element

>>> tuple2 = ("Hello",)

>>> tuple2 * 4

('Hello', 'Hello', 'Hello', 'Hello')

Membership
The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')

>>> 'Green' in tuple1 True

The not in operator returns True if the element is not present in the
tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')

>>> 'Green' not in tuple1 False

Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple

>>> tuple1 = (10,20,30,40,50,60,70,80)

#elements from index 2 to index 6

>>> tuple1[2:7] (30, 40, 50, 60, 70)

#all elements of tuple are printed

>>> tuple1[0:len(tuple1)]

(10, 20, 30, 40, 50, 60, 70, 80)

#slice starts from zero index

>>> tuple1[:5]

(10, 20, 30, 40, 50)

#slice is till end of the tuple

>>> tuple1[2:]

Nisha S K, Assistant Professor, SVIT Page 35


Python Programming-21EC643

(30, 40, 50, 60, 70, 80)

#step size 2

>>> tuple1[0:len(tuple1):2] (10,


30, 50, 70)
#negative indexing
>>> tuple1[-6:-4] (30,
40)

#tuple is traversed in reverse order

>>> tuple1[::-1]

(80, 70, 60, 50, 40, 30, 20, 10)

TUPLE METHODS AND BUILT-IN FUNCTIONS(SUMMARY)


Method Description Example
Returns the length or >>> tuple1 = (10,20,30,40,50)
the number of
len() elements of the tuple >>>
passed as the len(tuple1)
5
argument
>>> tuple1 = tuple()
>>> tuple1
()
>>> tuple1 = tuple('aeiou')#string
Creates an empty tuple >>> tuple1
if no argument. ('a', 'e', 'i', 'o', 'u')
tuple() Creates a tuple if a
>>> tuple2 = tuple([1,2,3]) #list
sequence is passed as
argument >>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
tuple1 =
count() >>>
Returns the number of (10,20,30,10,40,10,50)
times the given >>> tuple1.count(10)
element appears in the 3
tuple >>> tuple1.count(90)
0

Nisha S K, Assistant Professor, SVIT Page 36


Python Programming-21EC643

>>> tuple1 = (10,20,30,40,50)


Returns the index of >>> tuple1.index(30)
the
index() 2
occurrence of the
element in given tuple >>> tuple1.index(90)
ValueError: tuple.index(x): x not in
tuple
>>> tuple1 = ("Rama","Heena","Raj",
Takes elements in the "Mohsin","Aditya")
tuple and returns a >>> sorted(tuple1)
new sorted list. It
sorted() should be noted that,
sorted() does not make ['Aditya', 'Heena', 'Mohsin', 'Raj',
any change to the 'Rama']
original tuple

Returns minimum or >>> tuple1 = (19,12,56,18,9,87,34)


min() smallest element of the
tuple >>> min(tuple1)
9

Returns maximum or >>> max(tuple1)


max() largest element of the
tuple
87

Returns sum of the >>> sum(tuple1)


sum()
elements of thetuple
235

TUPLE ASSIGNMENT
Assignment of tuple is a useful feature in Python. It allows a
tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The
number of variables on the left should be same as the number of
elements in the tuple.

Example

#The first element 10 is assigned to num1 and

#the second element 20 is assigned to num2.

Nisha S K, Assistant Professor, SVIT Page 37


Python Programming-21EC643

>>> (num1,num2) = (10,20)

>>> print(num1) 10

>>> print(num2) 20

>>> record = ( "Pooja",40,"CS")


>>> (name,rollNo,subject) = record

>>> name 'Pooja'

>>> rollNo 40

>>> subject 'CS'

>>> (a,b,c,d) = (5,6,8)


ValueError: not enough values to unpack (expected 4, got 3)

If there is an expression on the right side then first that expression


is evaluated and finally the result is assigned to the tuple.
Example

#15 is assigned to num3 and #25


is assigned to num4
>>> (num3,num4) = (10+5,20+5)
>>> print(num3) 15

>>> print(num4) 25

Write a program to swap two numbers without using a temporary


variable.

num1 = int(input('Enter the first number: '))

num2 = int(input('Enter the second number: '))

print("\nNumbers before swapping:")

print("First Number:",num1)

print("Second Number:",num2)

(num1,num2) = (num2,num1)

Nisha S K, Assistant Professor, SVIT Page 38


Python Programming-21EC643

print("\nNumbers after swapping:")

print("First Number:",num1)

print("Second Number:",num2)

Output:

Enter the first number: 10

Enter the second number: 20

Numbers before swapping:

First Number: 10

Second Number: 20

Numbers after swapping:

First Number: 20

Second Number: 10

Write a program to input n numbers from the user. Store these numbers
in a tuple. Print the maximum and minimum number from this tuple.

numbers = tuple()
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))

Nisha S K, Assistant Professor, SVIT Page 39


Python Programming-21EC643

Output:
How many numbers you want to enter?: 5
1
2
3
4
5

The numbers in the tuple are:


(1, 2, 3, 4, 5)

The maximum number is:


5
The minimum number is:
1

References
 Technically, variables are storing references to the computer memory
locations where the values are stored.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
 When you assign 42 to the spam variable, you are actually creating
the 42 value in the computer’s memory and storing a reference to it in the
spam variable. When you copy the value in spam and assign it to the
variable cheese, you are actually copying the reference. Both
the spam and cheese variables refer to the 42 value in the computer’s
memory. When you later change the value in spam to 100, you’re creating a
new 100 value and storing a reference to it in spam. This doesn’t affect the
value in cheese. Integers are immutable values that don’t change; changing
the spam variable is actually making it refer to a completely different value in
memory.
 But lists don’t work this way, because list values can change; that is, lists

Nisha S K, Assistant Professor, SVIT Page 40


Python Programming-21EC643

are mutable.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam # The reference is being copied, not the list.
>>> cheese[1] = 'Hello!' # This changes the list value.
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese # The cheese variable refers to the same list.
[0, 'Hello!', 2, 3, 4, 5]

Identity and the id() Function


 All values in Python have a unique identity that can be obtained with
the id() function.
>>> id('Howdy') # The returned number will be different on your machine.
44491136
 When Python runs id('Howdy'), it creates the 'Howdy' string in the
computer’s memory. The numeric memory address where the string is stored
is returned by the id() function.
 Like all strings, 'Howdy' is immutable and cannot be changed. If you
“change” the string in a variable, a new string object is being made at a
different place in memory, and the variable refers to this new string.

Nisha S K, Assistant Professor, SVIT Page 41


Python Programming-21EC643

>>> bacon = 'Hello'


>>> id(bacon)
44491136
>>> bacon += ' world!' # A new string is made from 'Hello' and ' world!'.
>>> id(bacon) # bacon now refers to a completely different string.
44609712
 However, lists can be modified because they are mutable objects.
The append() method doesn’t create a new list object; it changes the existing
list object. We call this “modifying the object in-place.”
>>> eggs = ['cat', 'dog'] # This creates a new list.
>>> id(eggs)
35152584
>>> eggs.append('moose') # append() modifies the list "in place".
>>> id(eggs) # eggs still refers to the same list as before.
35152584
>>> eggs = ['bat', 'rat', 'cow'] # This creates a new list, which has a new
identity.
>>> id(eggs) # eggs now refers to a completely different list.
44409800
 If two variables refer to the same list (like spam and cheese in the
previous section) and the list value itself changes, both variables are affected
because they both refer to the same list.
The append(), extend(), remove(), sort(), reverse(), and other list methods
modify their lists in place.
 Python’s automatic garbage collector deletes any values not being referred
to by any variables to free up memory.

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.
Example:
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)

Nisha S K, Assistant Professor, SVIT Page 42


Python Programming-21EC643

print(spam)

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, copy.copy(), can be
used to make a duplicate copy of a mutable value like a list or dictionary, not
just a copy of a reference.
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> id(spam)
44684232
>>> cheese = copy.copy(spam)
>>> id(cheese) # cheese is a different list with different identity.
44685832
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']

Nisha S K, Assistant Professor, SVIT Page 43


Python Programming-21EC643

The Dictionary Data Type


 A dictionary is a collection of key-value pairs, where each key is unique
and associated with a value. Dictionaries are created using curly braces { },
and each key-value pair is separated by a colon :.
 Example:
my_dict = {"apple": 3, "banana": 2, "orange": 4}
In this dictionary, "apple", "banana", and "orange" are keys, and 3, 2, and
4 are their corresponding values.
Advantages of using dictionaries over lists:
 Fast Lookups: Dictionaries are optimized for fast lookups, which
means you can easily access the value associated with a given key
without having to search through the entire dictionary. This makes
dictionaries ideal for storing and accessing large amounts of data.
 Unordered: Unlike lists, dictionaries are unordered. This means that
the order in which you add items to the dictionary is not preserved.
However, you can still access items in a dictionary using their keys.
 Key-Value Pairs: Dictionaries allow you to store data in key-value
pairs, which can be more intuitive than storing data in a flat list. This
can make your code easier to read and understand.
 Dynamic Size: Dictionaries can grow and shrink dynamically, which
means you don't need to know the size of the dictionary in advance.
This can be especially useful when you're working with large amounts
of data that may change over time.
How a dictionary is created:
 A dictionary is created using curly braces {} and key-value pairs
separated by a colon :. Here is an example of a dictionary that stores
the population of three cities:
population = {"New York City": 8537673, "Los Angeles": 3976322,
"Chicago": 2693976}
 In this example, "New York City", "Los Angeles", and "Chicago" are
keys, and 8537673, 3976322, and 2693976 are their corresponding
values.
 You can also create an empty dictionary like this:
empty_dict = {}
 To add new items to the dictionary, you can simply assign a value to a
new key, like this: population["Houston"] = 2325502

Nisha S K, Assistant Professor, SVIT Page 44


Python Programming-21EC643

 In this example, a new key "Houston" is added to the dictionary, with


the value 2325502.
 To access the value associated with a key, you can use the square
bracket notation, like this: print(population["Los Angeles"])
 This will output 3976322, which is the population of Los Angeles.
 If you try to access a key that does not exist in the dictionary, a
KeyError will be raised.
 Examples:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> myCat['size']
'fat‘
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
 Dictionaries can still use integer values as keys, just like lists use
integers for indexes, but they do not have to start at 0 and can be any
number.
Example:
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}

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.
>>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):

Nisha S K, Assistant Professor, SVIT Page 45


Python Programming-21EC643

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


spam['color']
KeyError: 'color'

Example:
Predict data about Friend’s birthday:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

Output:
Enter a name: (blank to quit)
Alex
I do not have birthday information for Alex
What is their birthday?
June 21
Birthday database updated.
Enter a name: (blank to quit)
Alex
June 21 is the birthday of Alex
Enter a name: (blank to quit)

Nisha S K, Assistant Professor, SVIT Page 46


Python Programming-21EC643

The keys(), values(), and items() 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.
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
... print(v)

red
42
>>> for k in spam.keys():
... print(k)

color
age
>>> for i in spam.items():
... print(i)

('color', 'red')
('age', 42)
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
 The list(spam.keys()) line takes the dict_keys value returned
from keys() and passes it to list(), which then returns a list value of ['color',
'age'].
 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 spam.items():
... print('Key: ' + k + ' Value: ' + str(v))

Nisha S K, Assistant Professor, SVIT Page 47


Python Programming-21EC643

Key: age Value: 42


Key: color Value: red

Checking Whether a Key or Value Exists in a Dictionary


>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False

The get() Method


 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, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
 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['eggs']) + ' eggs.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'

The setdefault() Method


 The first argument passed to the method is the key to check for, and
the second argument is the value to set at that key if the key does not exist.
If the key does exist, the setdefault() method returns the key’s value.

Nisha S K, Assistant Professor, SVIT Page 48


Python Programming-21EC643

>>> spam = {'name': 'Pooka', 'age': 5}


>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
 The first time setdefault() is called, the dictionary in spam changes
to {'color': 'black', 'age': 5, 'name': 'Pooka'}. The method returns the
value 'black' because this is now the value set for the key 'color'.
When spam.setdefault('color', 'white') is called next, the value for that key
is not changed to 'white', because spam already has a key named 'color'.

Program to check the repetition of words


message = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Output:
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}

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 = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

Nisha S K, Assistant Professor, SVIT Page 49


Python Programming-21EC643

Output:
{' ': 1, '!': 1, 'H': 1, 'W': 1, 'd': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1}

A Tic_Tac_Toe Board

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M':
' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}

def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)

Nested Dictionaries and Lists

allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3,


'apples': 2},'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')

Nisha S K, Assistant Professor, SVIT Page 50


Python Programming-21EC643

print(' - Apples ' + str(totalBrought(allGuests, 'apples')))


print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

Output:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1

Write a Python program to input information about a few employees as


given below: a. Name b. Employee Id c. Salary The program should
output the employee ID and salary of a specified employee, given his
name.

employees = {}
while True:
name = input("Enter employee name (or 'quit' to exit): ")
if name == "quit":
break
emp_id = input("Enter employee ID: ")
salary = input("Enter employee salary: ")
employees[name] = {"id": emp_id, "salary": salary}
while True:
lookup_name = input("Enter the name of the employee to look up: ")
if lookup_name == "end":
break
if lookup_name in employees:
emp_id = employees[lookup_name]["id"]
salary = employees[lookup_name]["salary"]
print(f"Employee ID: {emp_id}")

Nisha S K, Assistant Professor, SVIT Page 51


Python Programming-21EC643

print(f"Employee salary: {salary}")


else:
print("Employee not found")

Write Python code to create a dictionary that accepts a country name as


a key and its capital city as the value. Display the details in sorted
order.

capitals={}
n = int(input("Enter the number of cities to add:"))
for i in range(n):
key=input("Enter country name:")
value=input("Enter its capital:")
capitals[key]=value
sorted_capitals = dict(sorted(capitals.items()))
for country, capital in sorted_capitals.items():
print("The capital of {} is {}".format(country, capital))

Write a Python program to accept ‘n’ numbers from the user. Find the
sum of all even numbers and the product of all odd numbers in the
entered list.

list=[]
n=int(input('Enter the number of elements in the list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
a=0
b=1
for i in range(n+1):
if i%2==0:
a+=i
else:
b*=i
print("Sum of even numbers=",a)
print("Product of odd numers=",b)

Nisha S K, Assistant Professor, SVIT Page 52


Python Programming-21EC643

Output:
Enter the number of elements in the list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
Enter the value: 4
Enter the value: 5
Sum of even numbers= 6
Product of odd numers= 15

Read N numbers from the console and create a list. Develop a program
to print mean, variance and standard deviation with suitable messages.

from math import sqrt


list=[]
n=int(input('Enter the number of elemnts in your list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
total=0
for i in range(n):
total+=n
mean=total/n
total=0
for i in range(n):
total+=(i-mean)**2
var=total/n
SD=sqrt(var)
print('Mean=',mean)
print('Variance=',var)
print('Standard Deviation=',SD)

Output:
Enter the number of elemnts in your list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3

Nisha S K, Assistant Professor, SVIT Page 53


Python Programming-21EC643

Enter the value: 4


Enter the value: 5
Mean= 5.0
Variance= 11.0
Standard Deviation= 3.3166247903554

Create a DB using dictionaries containing key as USN and related


fields containing Name, gender, Marks1, Marks2 & Marks3 of students.
Implement the following functions to perform i) Update
Name/gender/marks ii) search for usn and display the relevant fields iii)
delete based on search for name iv)generate the report with avg marks
more than 70%

student_db = {}

def add_student(usn, name, gender, marks1, marks2, marks3):


student_db[usn] = {
"Name": name,
"Gender": gender,
"Marks1": marks1,
"Marks2": marks2,
"Marks3": marks3
}

def update_student(usn, name=None, gender=None, marks1=None,


marks2=None, marks3=None):
if usn in student_db:
if name:
student_db[usn]["Name"] = name
if gender:
student_db[usn]["Gender"] = gender
if marks1 is not None:
student_db[usn]["Marks1"] = marks1
if marks2 is not None:
student_db[usn]["Marks2"] = marks2
if marks3 is not None:
student_db[usn]["Marks3"] = marks3
else:

Nisha S K, Assistant Professor, SVIT Page 54


Python Programming-21EC643

print("Student with USN", usn, "not found.")

def search_student_by_usn(usn):
return student_db.get(usn, "Student not found.")

def delete_student_by_name(name):
usns_to_delete = [usn for usn, details in student_db.items() if details["Name"]
== name]
for usn in usns_to_delete:
del student_db[usn]

def generate_report():
report = {}
for usn, details in student_db.items():
avg_marks = (details["Marks1"] + details["Marks2"] + details["Marks3"]) / 3
if avg_marks > 70:
report[usn] = details
return report

def main():
while True:
print("\nStudent Database Menu:")
print("1. Add Student")
print("2. Update Student")
print("3. Search Student by USN")
print("4. Delete Student by Name")
print("5. Generate Report (Avg Marks > 70%)")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
usn = input("Enter USN: ")
name = input("Enter Name: ")
gender = input("Enter Gender: ")
marks1 = float(input("Enter Marks1: "))
marks2 = float(input("Enter Marks2: "))
marks3 = float(input("Enter Marks3: "))
add_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student {name} added successfully.")

Nisha S K, Assistant Professor, SVIT Page 55


Python Programming-21EC643

elif choice == '2':


usn = input("Enter USN to update: ")
name = input("Enter new Name (leave blank to skip): ") or None
gender = input("Enter new Gender (leave blank to skip): ") or None
marks1 = input("Enter new Marks1 (leave blank to skip): ")
marks2 = input("Enter new Marks2 (leave blank to skip): ")
marks3 = input("Enter new Marks3 (leave blank to skip): ")
marks1 = float(marks1) if marks1 else None
marks2 = float(marks2) if marks2 else None
marks3 = float(marks3) if marks3 else None
update_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student with USN {usn} updated successfully.")
elif choice == '3':
usn = input("Enter USN to search: ")
result = search_student_by_usn(usn)
print("Search Result:", result)
elif choice == '4':
name = input("Enter Name to delete: ")
delete_student_by_name(name)
print(f"Student(s) with name {name} deleted successfully.")
elif choice == '5':
report = generate_report()
print("Report of students with average marks > 70%:")
for usn, details in report.items():
print(f"USN: {usn}, Details: {details}")
elif choice == '6':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Write a program to enter names of employees and their salaries as input and
store them in a dictionary.

num = int(input("Enter the number of employees whose data to be stored: "))

Nisha S K, Assistant Professor, SVIT Page 56


Python Programming-21EC643

count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])

Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000

****End****

Nisha S K, Assistant Professor, SVIT Page 57


Python Programming-21EC643

Module 2

Lists, Tuples and Dictionaries

Data Structures: Lists: The List Data Type, Working with Lists Strings: Manipulating Strings,
Working with Strings, Useful String Methods Tuples and Dictionaries, basics Using Data
Structures to Model Real-World Things, Manipulating Strings.

The List Data Type

 A list in Python is a collection of ordered items, which can be of any data


type, such as numbers, strings, or other objects. Lists are written in square
brackets, with items separated by commas. For example:
numbers = [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry"]
 The data type list is an ordered sequence which is mutable and made up of
one or more elements.
 Unlike a string which consists of only characters, a list can have elements of
different data types, such as integer, float, string, tuple or even another list.
 A list is very useful to group together elements of mixed data types.
 Elements of a list are enclosed in square brackets and are separated by
comma. Like string indices, list indices also start from 0.
 A list begins with an opening square bracket and ends with a closing square
bracket, [ ].
 Values inside the list are also called items.
 Items are separated with commas (that is, they are comma-delimited).
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
#list2 is the list of vowels
>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']

Nisha S K, Assistant Professor, SVIT Page 1


Python Programming-21EC643

>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested list
>>> list4 =[['Physics',101],['Chemistry',202], ['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202], ['Maths', 303]]

Getting Individual Values in a List with Indexes (Accessing Elements in


a List)

 Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam.
 The Python code spam[0] would evaluate to 'cat', and 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.

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


>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat‘
>>> spam=[1,2,3,4,5]
>>> spam[4]
5
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant‘
>>> 'Hello, ' + spam[0]
'Hello, cat’

Nisha S K, Assistant Professor, SVIT Page 2


Python Programming-21EC643

>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.‘
'The bat ate the cat.'
>>> spam=[1,2,3,4,5]
>>> 'I ate',spam[1],'Dosas today.‘
('I ate', 2, 'Dosas today.')
>>> 'I ate'+spam[1]+'Dosas today.’
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError:
can only concatenate str (not "int") to str
>>> 'I ate '+str(spam[1])+' Dosas today.‘
'I ate 2 Dosas today.'
Python will give you an IndexError error message if you use an index
that exceeds the number of values in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
 Indexes can be only integer values, not floats. The following example
will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
 Lists can also contain other list values. The values in these lists of lists
can be accessed
Using multiple indexes, like so:
>>> spam=[['Hi','Hello'],[‘Will',‘Dave',‘Tom',‘Chris']]
>>> spam[0]

Nisha S K, Assistant Professor, SVIT Page 3


Python Programming-21EC643

['Hi', 'Hello']
>>> spam[1]
[‘Will',‘Dave',‘Tom',‘Chris']
>>> spam[0][1]
'Hello’
>>> spam[1][2]
'Tom‘
>>> 'I want to tell '+str(spam[0][0])+' '+str(spam[1][0])
'I want to tell Hi Will'

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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'

Lists are Mutable

 In Python, lists are mutable.


 It means that the contents of the list can be changed after it has been
created.
#List list1 of colors
>>> list1 = ['Red','Green','Blue','Orange']
#change/override the fourth element of list1
>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

Nisha S K, Assistant Professor, SVIT Page 4


Python Programming-21EC643

Getting a List from another List with Slices

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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
#list1 is truncated to the end of the list
>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[7:2] #first index > second index
[ ] #results in an empty list
#return sublist from index 0 to 4
>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']

Nisha S K, Assistant Professor, SVIT Page 5


Python Programming-21EC643

#slicing with a given step size


>>> list1[0:6:2]
['Red','Blue','Magenta']
#negative indexes
#elements at index -6,-5,-4,-3 are sliced
>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta']
#both first and last index missing
>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']
#negative step size
#whole list in the reverse order
>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']

Getting a List’s Length with the len() Function


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.
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3

Changing Values in a List with Indexes


 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'.”
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]

Nisha S K, Assistant Professor, SVIT Page 6


Python Programming-21EC643

>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]

List Concatenation and List Replication


 Lists can be concatenated and replicated just like strings.
 The + operator combines two lists to create a new list value and
the * operator can be used with a list and an integer value to replicate the
list.
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']

Removing Values from Lists with del Statements


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]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

Traversing a List

We can access each element of the list or traverse a list using a for loop or a
while loop.

Nisha S K, Assistant Professor, SVIT Page 7


Python Programming-21EC643

(A) List Traversal Using for Loop:


>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black

Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black

(B) List Traversal Using while Loop:

>>> list1 = ['Red','Green','Blue','Yellow', 'Black']


>>> i = 0
>>> while i < len(list1):
print(list1[i]) i += 1
Output:
Red
Green
Blue
Yellow
Black

Nisha S K, Assistant Professor, SVIT Page 8


Python Programming-21EC643

Working with Lists

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)

Output:
Enter the name of cat 1 (Or enter nothing to stop.):
Pooka
Enter the name of cat 2 (Or enter nothing to stop.):
eer
Enter the name of cat 3 (Or enter nothing to stop.):

The cat names are:


Pooka
Eer

The in and not in Operators (Membership)


 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.
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False

Nisha S K, Assistant Professor, SVIT Page 9


Python Programming-21EC643

>>> 'cat' not in spam


True

Example:

myPets = ['Zophie', 'Pooka', 'Fat-tail']


print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

Output:

Enter a pet name:


Err
I do not have a pet named Err

The Multiple Assignment Trick


 The multiple assignment trick (technically called tuple unpacking) 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:
>>> cat = ['fat', 'gray', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition = cat
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

Nisha S K, Assistant Professor, SVIT Page 10


Python Programming-21EC643

Using the enumerate() Function with Lists

 Instead of using the range(len(someList)) technique with a for loop to


obtain the integer index of the items in the list, you can call
the enumerate() function instead. On each iteration of the
loop, enumerate() will return two values: the index of the item in the list, and
the item in the list itself.
>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
>>> for index, item in enumerate(supplies):
... print('Index ' + str(index) + ' in supplies is: ' + item)

Index 0 in supplies is: pens


Index 1 in supplies is: staplers
Index 2 in supplies is: flamethrowers
Index 3 in supplies is: binders

Using the random.choice() and random.shuffle() Functions with Lists

 The random module has a couple functions that accept lists for
arguments. The random.choice() function will return a randomly selected
item from the list.
>>> import random
>>> pets = ['Dog', 'Cat', 'Moose']
>>> random.choice(pets)
'Dog'
>>> random.choice(pets)
'Cat'
>>> random.choice(pets)
'Cat'
 The random.shuffle() function will reorder the items in a list. This function
modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)

Nisha S K, Assistant Professor, SVIT Page 11


Python Programming-21EC643

>>> people
['Alice', 'David', 'Bob', 'Carol']

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:

>>> spam = 42
>>> spam = spam + 1
>>> spam
43

As a shortcut, you can use the augmented assignment operator += to do the


same thing:

>>> spam = 42
>>> spam += 1
>>> spam
43

Nisha S K, Assistant Professor, SVIT Page 12


Python Programming-21EC643

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

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.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
 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', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1

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


 To add new values to a list, use the append() and insert() methods.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam

Nisha S K, Assistant Professor, SVIT Page 13


Python Programming-21EC643

['cat', 'dog', 'bat', 'moose']


 The previous append() method call adds the argument to the end of the
list. 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.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
 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.
>>> eggs = 'hello'
>>> eggs.append('world')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
eggs.append('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> bacon.insert(1, 'world')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'

Removing Values from Lists with the remove() Method

 The remove() method is passed the value to be removed from the list it is
called on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
 Attempting to delete a value that does not exist in the list will result in
a ValueError error.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')

Nisha S K, Assistant Professor, SVIT Page 14


Python Programming-21EC643

Traceback (most recent call last):


File "<pyshell#11>", line 1, in <module>
spam.remove('chicken')
ValueError: list.remove(x): x not in list
 If the value appears multiple times in the list, only the first instance of the
value will be removed.
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('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 useful when you
know the value you want to remove from the list.

Sorting the Values in a List with the sort() Method

 Lists of number values or lists of strings can be sorted with


the sort() method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
 You can also pass True for the reverse keyword argument to
have sort() sort the values in reverse order.
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
 There are three things you should note about the sort() method. First,
the sort() method sorts the list in place; don’t try to capture the return value
by writing code like spam = spam.sort().
 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.

Nisha S K, Assistant Professor, SVIT Page 15


Python Programming-21EC643

>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']


>>> spam.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
spam.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
 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)
>>> spam
['a', 'A', 'z', 'Z']

Reversing the Values in a List with the reverse() Method

 If you need to quickly reverse the order of the items in a list, you can call
the reverse() list method.
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']

Magic 8 Ball with a List

import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',

Nisha S K, Assistant Professor, SVIT Page 16


Python Programming-21EC643

'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)])

The above program gives us output randomly picking any string from the list.
The output changes whenever it is executed.

List Methods and Built-in Functions(Summary)

Method Description Example

>>> list1 = [10,20,30,40,50]


Returns the length of
len() the list passed as the >>> len(list1)
argument 5

>>> list1 = list()


Creates an empty list if
no argument is passed >>> list1
[]
list() >>> str1 = 'aeiou'
Creates a list if a >>> list1 = list(str1)
sequence is passed as
>>> list1
an argument
['a', 'e', 'i', 'o', 'u']
>>> list1 = [10,20,30,40]
Appends a single >>> list1.append(50)
element passed as an >>> list1
argument at the end of [10, 20, 30, 40, 50]
append()
the list. The single >>> list1 = [10,20,30,40]
element can also be a >>> list1.append([50,60])
list
>>> list1
[10, 20, 30, 40, [50, 60]]
Appends each element >>> list1 = [10,20,30]
extend()
of the list passed as >>> list2 = [40,50]

Nisha S K, Assistant Professor, SVIT Page 17


Python Programming-21EC643

argument to the end of >>> list1.extend(list2)


the given list >>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
Inserts an element at a >>> list1
insert() particular index in the [10, 20, 25, 30, 40, 50]
list >>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
>>> list1 =
Returns the number of [10,20,30,10,40,10]
count() times a given element >>> list1.count(10) 3
appears in the list >>> list1.count(90)
0
Returns index of the >>> list1 =
first occurrence of the [10,20,30,20,40,10]
element in the list. If
index() >>> list1.index(20) 1
the element is not
present, ValueError is >>> list1.index(90)
generated ValueError: 90 is not in list
Removes the given >>> list1 =
element from the list. [10,20,30,40,50,30]
If the element is >>> list1.remove(30)
present multiple times, >>> list1
only the first
remove() [10, 20, 40, 50, 30]
occurrence is removed.
If the element is not >>> list1.remove(90)
present, then ValueError:list.remove(x):x
ValueError is not in list
generated
Returns the element >>> list1 =
whose index is passed [10,20,30,40,50,60]
as parameter to this >>> list1.pop(3) 40
function and also >>> list1
pop() removes it from the
[10, 20, 30, 50, 60]
list. If no parameter is
given, then it returns >>> list1 =
and removes the last [10,20,30,40,50,60]
element of the list >>> list1.pop() 60
>>> list1

Nisha S K, Assistant Professor, SVIT Page 18


Python Programming-21EC643

[10, 20, 30, 40, 50]


>>> list1 =
[34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
Reverses the order of
>>> list1 = [ 'Tiger' ,'Zebra' ,
reverse() elements in the given
'Lion' , 'Cat' ,'Elephant'
list
,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat',
'Lion', 'Zebra', 'Tiger']
>>>list1 =
['Tiger','Zebra','Lion',
'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
Sorts the elements of ['Cat', 'Dog', 'Elephant',
sort()
the given list in-place 'Lion', 'Tiger', 'Zebra']
>>> list1 =
[34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
>>> list1 =
It takes a list as [23,45,11,67,85,56]
parameter and creates >>> list2 = sorted(list1)
a new list consisting of
sorted() >>> list1
the same elements
arranged in sorted [23, 45, 11, 67, 85, 56]
order >>> list2
[11, 23, 45, 56, 67, 85]
>>> list1 =
Returns minimum or [34,12,63,39,92,44]
min() smallest element of
the list >>> min(list1) 12

Returns maximum or
max() largest element of the >>> max(list1) 92
list

Nisha S K, Assistant Professor, SVIT Page 19


Python Programming-21EC643

Returns sum of the >>> sum(list1)


sum()
elements of the list
284

Sequence Data Types

 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.
 The Python sequence data types include lists, strings, range objects
returned by range(), and tuples.
 Many of the things you can do with lists can also be done with strings and
other values of sequence types: indexing; slicing; and using them
with for loops, with len(), and with the in and not in operators.
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *')

* * * Z***
* * * o***
* * * p***
* * * h***
* * * i***
* * * e***

Nisha S K, Assistant Professor, SVIT Page 20


Python Programming-21EC643

Mutable and Immutable Data Types

 A list value is a mutable data type: it can have values added, removed, or
changed. However, a string is immutable: it cannot be changed.
>>> 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
 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='My name Nisha'
>>> newname=name[0:7]+‘ is '+name[8:13]
‘My name is Nisha’
 Although a list value is mutable.
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[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])

 For modifying we use the method below.


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

Nisha S K, Assistant Professor, SVIT Page 21


Python Programming-21EC643

>>> del eggs[2]


>>> del eggs[1]
>>> del eggs[0]
>>> eggs.append(4)
>>> eggs.append(5)
>>> eggs.append(6)
>>> eggs
[4, 5, 6]

Nested Lists

 When a list appears as an element of another list, it is called a nested list.


>>> list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
 To access the element of the nested list of list1, we have to specify two
indices list1[i][j].
 The first index i will take us to the desired nested list and second index j
will take us to the desired element in that nested list.
>>> list1[4][1]
7

Nisha S K, Assistant Professor, SVIT Page 22


Python Programming-21EC643

Copying Lists:

 Given a list, the simplest way to make a copy of the list is to assign it to
another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
 The statement list2 = list1 does not create a new list.
 Rather, it just makes list1 and list2 refer to the same list object.
 Here list2 actually becomes an alias of list1.
 Therefore, any changes made to either of them will be reflected in the
other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
 We can also create a copy or clone of the list as a distinct object by three
methods.
 The first method uses slicing, the second method uses built-in function
list() and the third method uses copy() function of python library copy.
Method 1
 We can slice our original list and store it into a new variable as follows:
newList = oldList[:]
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2
We can use the built-in function list() as follows:
newList = list(oldList)

Nisha S K, Assistant Professor, SVIT Page 23


Python Programming-21EC643

>>> list1 = [10,20,30,40]


>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]
Method 3
We can use the copy () function as follows:
import copy #import the library copy
#use copy()function of library copy
newList = copy.copy(oldList)
Example
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2
[1, 2, 3, 4, 5]

Program to increment the elements of a list. The list is passed as an


argument to a function.

def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print('Reference of list Inside Function',id(list2))
list1 = [10,20,30,40,50] #Create a list
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)
Output:
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 140290458650304
The list after the function call
[15, 25, 35, 45, 55]

Nisha S K, Assistant Professor, SVIT Page 24


Python Programming-21EC643

Program to increment the elements of the list passed as parameter.

def increment(list2):
print("\nID of list inside function before assignment:",id(list2))
list2 = [15,25,35,45,55] #List2 assigned a new list
print("ID of list changes inside function after assignment:",id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)

Output:
ID of list before function call: 140642743551680
The list before function call:
[10, 20, 30, 40, 50]

ID of list inside function before assignment: 140642743551680


ID of list changes inside function after assignment: 140642742108608
The list inside the function after assignment is:
[15, 25, 35, 45, 55]

ID of list after function call: 140642743551680


The list after the function call:
[10, 20, 30, 40, 50]

List Manipulation:
Write a menu driven program to perform various list operations, such
as:
• Append an element
• Insert an element

Nisha S K, Assistant Professor, SVIT Page 25


Python Programming-21EC643

• Append a list to the given list


• Modify an existing element
• Delete an existing element from its position
• Delete an existing element with a given value
• Sort the list in ascending order
• Sort the list in descending order
• Display the list.

myList = [22,4,16,38,13]
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")

Nisha S K, Assistant Professor, SVIT Page 26


Python Programming-21EC643

elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()

Nisha S K, Assistant Professor, SVIT Page 27


Python Programming-21EC643

Output:

The list 'myList' has the following elements [22, 4, 16, 38, 13]

LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 7

The list has been sorted


The list 'myList' has the following elements [4, 13, 16, 22, 38]

LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 8

The list has been sorted in reverse order


The list 'myList' has the following elements [38, 22, 16, 13, 4]

LISTOPERATIONS
1. Append an element

Nisha S K, Assistant Professor, SVIT Page 28


Python Programming-21EC643

2. Insert an element at the desired position


3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 10

A program to calculate average marks of n students using a function


where n is entered by the user.

def computeAverage(list1,n):
total = 0
for marks in list1:
total = total + marks
average = total / n
return average
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)

Output:
How many students marks you want to enter:
5
Enter marks of student 1 :
45
Enter marks of student 2 :
89

Nisha S K, Assistant Professor, SVIT Page 29


Python Programming-21EC643

Enter marks of student 3 :


79
Enter marks of student 4 :
76
Enter marks of student 5 :
55
Average marks of 5 students is: 68.8

Write a user-defined function to check if a number is present in the list


or not. If the number is present, return the position of the number.
Print an appropriate message if the number is not present in the list.

def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")

Output:
How many numbers do you want to enter in the list:
5
Enter a list of numbers:
23
567
12

Nisha S K, Assistant Professor, SVIT Page 30


Python Programming-21EC643

89
324
Enter the number to be searched: 12
Number 12 is present at 3 position

The Tuple Data Type


 A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas.
 Like list and string, elements of a tuple can be accessed using index
values, starting from 0.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
 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.
 >>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
#tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
>>> tuple2 =('Economics',87,'Accountancy',89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
#tuple3 is the tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
(10, 20, 30, [40, 50])

Nisha S K, Assistant Professor, SVIT Page 31


Python Programming-21EC643

#tuple4 is the tuple with tuple as an element


>>> tuple4 = (1,2,3,4,5,(10,20))
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
 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, it’s fine to have a trailing comma after the last item in a list or
tuple in Python.)
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

Accessing Elements in a Tuple


 Elements of a tuple can be accessed in the same way as a list or string
using indexing and slicing.
>>> tuple1 = (2,4,6,8,10,12)
#initializes a tuple tuple1
#returns the first element of tuple1
>>> tuple1[0]
2
#returns fourth element of tuple1
>>> tuple1[3]
8
#returns error as index is out of range
>>> tuple1[15]
IndexError: tuple index out of range #an expression resulting in an
integer index
>>> tuple1[1+4]
12
#returns first element from right
>>> tuple1[-1]
12

Nisha S K, Assistant Professor, SVIT Page 32


Python Programming-21EC643

Tuple is Immutable
 Tuple is an immutable data type. It means that the elements of a tuple
cannot be changed after it has been created. An attempt to do this would
lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
 However an element of a tuple may be of mutable type, e.g., a list.
#4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple2
>>> tuple2[3][1] = 10
#modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])

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.
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Tuple Operations
Concatenation
Python allows us to join tuples using concatenation operator depicted
by symbol +. We can also create a new tuple which contains the result
of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)

>>> tuple2 = (2,4,6,8,10)

>>> tuple1 + tuple2 #concatenates two tuples

Nisha S K, Assistant Professor, SVIT Page 33


Python Programming-21EC643

(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

>>> tuple3 = ('Red','Green','Blue')

>>> tuple4 = ('Cyan', 'Magenta', 'Yellow'

,'Black')

#tuple5 stores elements of tuple3 and tuple4

>>> tuple5 = tuple3 + tuple4

>>> tuple5 ('Red','Green','Blue','Cyan','Magenta', 'Yellow','Black')

Concatenation operator can also be used for extending an existing


tuple. When we extend a tuple using concatenation a new tuple is
created.
>>> tuple6 = (1,2,3,4,5)

#single element is appended to tuple6

>>> tuple6 = tuple6 + (6,)

>>> tuple6

(1, 2, 3, 4, 5, 6)

#more than one elements are appended

>>> tuple6 = tuple6 + (7,8,9)

>>> tuple6

(1, 2, 3, 4, 5, 6, 7, 8, 9)

Repetition
Repetition operation is depicted by the symbol *. It is used to repeat
elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand
to be an integer only.
>>> tuple1 = ('Hello','World')

>>> tuple1 * 3

('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Nisha S K, Assistant Professor, SVIT Page 34


Python Programming-21EC643

#tuple with single element

>>> tuple2 = ("Hello",)

>>> tuple2 * 4

('Hello', 'Hello', 'Hello', 'Hello')

Membership
The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')

>>> 'Green' in tuple1 True

The not in operator returns True if the element is not present in the
tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')

>>> 'Green' not in tuple1 False

Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple

>>> tuple1 = (10,20,30,40,50,60,70,80)

#elements from index 2 to index 6

>>> tuple1[2:7] (30, 40, 50, 60, 70)

#all elements of tuple are printed

>>> tuple1[0:len(tuple1)]

(10, 20, 30, 40, 50, 60, 70, 80)

#slice starts from zero index

>>> tuple1[:5]

(10, 20, 30, 40, 50)

#slice is till end of the tuple

>>> tuple1[2:]

Nisha S K, Assistant Professor, SVIT Page 35


Python Programming-21EC643

(30, 40, 50, 60, 70, 80)

#step size 2

>>> tuple1[0:len(tuple1):2] (10,


30, 50, 70)
#negative indexing
>>> tuple1[-6:-4] (30,
40)

#tuple is traversed in reverse order

>>> tuple1[::-1]

(80, 70, 60, 50, 40, 30, 20, 10)

TUPLE METHODS AND BUILT-IN FUNCTIONS(SUMMARY)


Method Description Example
Returns the length or >>> tuple1 = (10,20,30,40,50)
the number of
len() elements of the tuple >>>
passed as the len(tuple1)
5
argument
>>> tuple1 = tuple()
>>> tuple1
()
>>> tuple1 = tuple('aeiou')#string
Creates an empty tuple >>> tuple1
if no argument. ('a', 'e', 'i', 'o', 'u')
tuple() Creates a tuple if a
>>> tuple2 = tuple([1,2,3]) #list
sequence is passed as
argument >>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
tuple1 =
count() >>>
Returns the number of (10,20,30,10,40,10,50)
times the given >>> tuple1.count(10)
element appears in the 3
tuple >>> tuple1.count(90)
0

Nisha S K, Assistant Professor, SVIT Page 36


Python Programming-21EC643

>>> tuple1 = (10,20,30,40,50)


Returns the index of >>> tuple1.index(30)
the
index() 2
occurrence of the
element in given tuple >>> tuple1.index(90)
ValueError: tuple.index(x): x not in
tuple
>>> tuple1 = ("Rama","Heena","Raj",
Takes elements in the "Mohsin","Aditya")
tuple and returns a >>> sorted(tuple1)
new sorted list. It
sorted() should be noted that,
sorted() does not make ['Aditya', 'Heena', 'Mohsin', 'Raj',
any change to the 'Rama']
original tuple

Returns minimum or >>> tuple1 = (19,12,56,18,9,87,34)


min() smallest element of the
tuple >>> min(tuple1)
9

Returns maximum or >>> max(tuple1)


max() largest element of the
tuple
87

Returns sum of the >>> sum(tuple1)


sum()
elements of thetuple
235

TUPLE ASSIGNMENT
Assignment of tuple is a useful feature in Python. It allows a
tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The
number of variables on the left should be same as the number of
elements in the tuple.

Example

#The first element 10 is assigned to num1 and

#the second element 20 is assigned to num2.

Nisha S K, Assistant Professor, SVIT Page 37


Python Programming-21EC643

>>> (num1,num2) = (10,20)

>>> print(num1) 10

>>> print(num2) 20

>>> record = ( "Pooja",40,"CS")


>>> (name,rollNo,subject) = record

>>> name 'Pooja'

>>> rollNo 40

>>> subject 'CS'

>>> (a,b,c,d) = (5,6,8)


ValueError: not enough values to unpack (expected 4, got 3)

If there is an expression on the right side then first that expression


is evaluated and finally the result is assigned to the tuple.
Example

#15 is assigned to num3 and #25


is assigned to num4
>>> (num3,num4) = (10+5,20+5)
>>> print(num3) 15

>>> print(num4) 25

Write a program to swap two numbers without using a temporary


variable.

num1 = int(input('Enter the first number: '))

num2 = int(input('Enter the second number: '))

print("\nNumbers before swapping:")

print("First Number:",num1)

print("Second Number:",num2)

(num1,num2) = (num2,num1)

Nisha S K, Assistant Professor, SVIT Page 38


Python Programming-21EC643

print("\nNumbers after swapping:")

print("First Number:",num1)

print("Second Number:",num2)

Output:

Enter the first number: 10

Enter the second number: 20

Numbers before swapping:

First Number: 10

Second Number: 20

Numbers after swapping:

First Number: 20

Second Number: 10

Write a program to input n numbers from the user. Store these numbers
in a tuple. Print the maximum and minimum number from this tuple.

numbers = tuple()
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))

Nisha S K, Assistant Professor, SVIT Page 39


Python Programming-21EC643

Output:
How many numbers you want to enter?: 5
1
2
3
4
5

The numbers in the tuple are:


(1, 2, 3, 4, 5)

The maximum number is:


5
The minimum number is:
1

References
 Technically, variables are storing references to the computer memory
locations where the values are stored.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
 When you assign 42 to the spam variable, you are actually creating
the 42 value in the computer’s memory and storing a reference to it in the
spam variable. When you copy the value in spam and assign it to the
variable cheese, you are actually copying the reference. Both
the spam and cheese variables refer to the 42 value in the computer’s
memory. When you later change the value in spam to 100, you’re creating a
new 100 value and storing a reference to it in spam. This doesn’t affect the
value in cheese. Integers are immutable values that don’t change; changing
the spam variable is actually making it refer to a completely different value in
memory.
 But lists don’t work this way, because list values can change; that is, lists

Nisha S K, Assistant Professor, SVIT Page 40


Python Programming-21EC643

are mutable.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam # The reference is being copied, not the list.
>>> cheese[1] = 'Hello!' # This changes the list value.
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese # The cheese variable refers to the same list.
[0, 'Hello!', 2, 3, 4, 5]

Identity and the id() Function


 All values in Python have a unique identity that can be obtained with
the id() function.
>>> id('Howdy') # The returned number will be different on your machine.
44491136
 When Python runs id('Howdy'), it creates the 'Howdy' string in the
computer’s memory. The numeric memory address where the string is stored
is returned by the id() function.
 Like all strings, 'Howdy' is immutable and cannot be changed. If you
“change” the string in a variable, a new string object is being made at a
different place in memory, and the variable refers to this new string.

Nisha S K, Assistant Professor, SVIT Page 41


Python Programming-21EC643

>>> bacon = 'Hello'


>>> id(bacon)
44491136
>>> bacon += ' world!' # A new string is made from 'Hello' and ' world!'.
>>> id(bacon) # bacon now refers to a completely different string.
44609712
 However, lists can be modified because they are mutable objects.
The append() method doesn’t create a new list object; it changes the existing
list object. We call this “modifying the object in-place.”
>>> eggs = ['cat', 'dog'] # This creates a new list.
>>> id(eggs)
35152584
>>> eggs.append('moose') # append() modifies the list "in place".
>>> id(eggs) # eggs still refers to the same list as before.
35152584
>>> eggs = ['bat', 'rat', 'cow'] # This creates a new list, which has a new
identity.
>>> id(eggs) # eggs now refers to a completely different list.
44409800
 If two variables refer to the same list (like spam and cheese in the
previous section) and the list value itself changes, both variables are affected
because they both refer to the same list.
The append(), extend(), remove(), sort(), reverse(), and other list methods
modify their lists in place.
 Python’s automatic garbage collector deletes any values not being referred
to by any variables to free up memory.

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.
Example:
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)

Nisha S K, Assistant Professor, SVIT Page 42


Python Programming-21EC643

print(spam)

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, copy.copy(), can be
used to make a duplicate copy of a mutable value like a list or dictionary, not
just a copy of a reference.
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> id(spam)
44684232
>>> cheese = copy.copy(spam)
>>> id(cheese) # cheese is a different list with different identity.
44685832
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']

Nisha S K, Assistant Professor, SVIT Page 43


Python Programming-21EC643

The Dictionary Data Type


 A dictionary is a collection of key-value pairs, where each key is unique
and associated with a value. Dictionaries are created using curly braces { },
and each key-value pair is separated by a colon :.
 Example:
my_dict = {"apple": 3, "banana": 2, "orange": 4}
In this dictionary, "apple", "banana", and "orange" are keys, and 3, 2, and
4 are their corresponding values.
Advantages of using dictionaries over lists:
 Fast Lookups: Dictionaries are optimized for fast lookups, which
means you can easily access the value associated with a given key
without having to search through the entire dictionary. This makes
dictionaries ideal for storing and accessing large amounts of data.
 Unordered: Unlike lists, dictionaries are unordered. This means that
the order in which you add items to the dictionary is not preserved.
However, you can still access items in a dictionary using their keys.
 Key-Value Pairs: Dictionaries allow you to store data in key-value
pairs, which can be more intuitive than storing data in a flat list. This
can make your code easier to read and understand.
 Dynamic Size: Dictionaries can grow and shrink dynamically, which
means you don't need to know the size of the dictionary in advance.
This can be especially useful when you're working with large amounts
of data that may change over time.
How a dictionary is created:
 A dictionary is created using curly braces {} and key-value pairs
separated by a colon :. Here is an example of a dictionary that stores
the population of three cities:
population = {"New York City": 8537673, "Los Angeles": 3976322,
"Chicago": 2693976}
 In this example, "New York City", "Los Angeles", and "Chicago" are
keys, and 8537673, 3976322, and 2693976 are their corresponding
values.
 You can also create an empty dictionary like this:
empty_dict = {}
 To add new items to the dictionary, you can simply assign a value to a
new key, like this: population["Houston"] = 2325502

Nisha S K, Assistant Professor, SVIT Page 44


Python Programming-21EC643

 In this example, a new key "Houston" is added to the dictionary, with


the value 2325502.
 To access the value associated with a key, you can use the square
bracket notation, like this: print(population["Los Angeles"])
 This will output 3976322, which is the population of Los Angeles.
 If you try to access a key that does not exist in the dictionary, a
KeyError will be raised.
 Examples:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> myCat['size']
'fat‘
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
 Dictionaries can still use integer values as keys, just like lists use
integers for indexes, but they do not have to start at 0 and can be any
number.
Example:
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}

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.
>>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):

Nisha S K, Assistant Professor, SVIT Page 45


Python Programming-21EC643

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


spam['color']
KeyError: 'color'

Example:
Predict data about Friend’s birthday:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

Output:
Enter a name: (blank to quit)
Alex
I do not have birthday information for Alex
What is their birthday?
June 21
Birthday database updated.
Enter a name: (blank to quit)
Alex
June 21 is the birthday of Alex
Enter a name: (blank to quit)

Nisha S K, Assistant Professor, SVIT Page 46


Python Programming-21EC643

The keys(), values(), and items() 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.
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
... print(v)

red
42
>>> for k in spam.keys():
... print(k)

color
age
>>> for i in spam.items():
... print(i)

('color', 'red')
('age', 42)
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
 The list(spam.keys()) line takes the dict_keys value returned
from keys() and passes it to list(), which then returns a list value of ['color',
'age'].
 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 spam.items():
... print('Key: ' + k + ' Value: ' + str(v))

Nisha S K, Assistant Professor, SVIT Page 47


Python Programming-21EC643

Key: age Value: 42


Key: color Value: red

Checking Whether a Key or Value Exists in a Dictionary


>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False

The get() Method


 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, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
 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['eggs']) + ' eggs.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'

The setdefault() Method


 The first argument passed to the method is the key to check for, and
the second argument is the value to set at that key if the key does not exist.
If the key does exist, the setdefault() method returns the key’s value.

Nisha S K, Assistant Professor, SVIT Page 48


Python Programming-21EC643

>>> spam = {'name': 'Pooka', 'age': 5}


>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
 The first time setdefault() is called, the dictionary in spam changes
to {'color': 'black', 'age': 5, 'name': 'Pooka'}. The method returns the
value 'black' because this is now the value set for the key 'color'.
When spam.setdefault('color', 'white') is called next, the value for that key
is not changed to 'white', because spam already has a key named 'color'.

Program to check the repetition of words


message = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Output:
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}

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 = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

Nisha S K, Assistant Professor, SVIT Page 49


Python Programming-21EC643

Output:
{' ': 1, '!': 1, 'H': 1, 'W': 1, 'd': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1}

A Tic_Tac_Toe Board

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M':
' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}

def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)

Nested Dictionaries and Lists

allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3,


'apples': 2},'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')

Nisha S K, Assistant Professor, SVIT Page 50


Python Programming-21EC643

print(' - Apples ' + str(totalBrought(allGuests, 'apples')))


print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

Output:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1

Write a Python program to input information about a few employees as


given below: a. Name b. Employee Id c. Salary The program should
output the employee ID and salary of a specified employee, given his
name.

employees = {}
while True:
name = input("Enter employee name (or 'quit' to exit): ")
if name == "quit":
break
emp_id = input("Enter employee ID: ")
salary = input("Enter employee salary: ")
employees[name] = {"id": emp_id, "salary": salary}
while True:
lookup_name = input("Enter the name of the employee to look up: ")
if lookup_name == "end":
break
if lookup_name in employees:
emp_id = employees[lookup_name]["id"]
salary = employees[lookup_name]["salary"]
print(f"Employee ID: {emp_id}")

Nisha S K, Assistant Professor, SVIT Page 51


Python Programming-21EC643

print(f"Employee salary: {salary}")


else:
print("Employee not found")

Write Python code to create a dictionary that accepts a country name as


a key and its capital city as the value. Display the details in sorted
order.

capitals={}
n = int(input("Enter the number of cities to add:"))
for i in range(n):
key=input("Enter country name:")
value=input("Enter its capital:")
capitals[key]=value
sorted_capitals = dict(sorted(capitals.items()))
for country, capital in sorted_capitals.items():
print("The capital of {} is {}".format(country, capital))

Write a Python program to accept ‘n’ numbers from the user. Find the
sum of all even numbers and the product of all odd numbers in the
entered list.

list=[]
n=int(input('Enter the number of elements in the list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
a=0
b=1
for i in range(n+1):
if i%2==0:
a+=i
else:
b*=i
print("Sum of even numbers=",a)
print("Product of odd numers=",b)

Nisha S K, Assistant Professor, SVIT Page 52


Python Programming-21EC643

Output:
Enter the number of elements in the list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
Enter the value: 4
Enter the value: 5
Sum of even numbers= 6
Product of odd numers= 15

Read N numbers from the console and create a list. Develop a program
to print mean, variance and standard deviation with suitable messages.

from math import sqrt


list=[]
n=int(input('Enter the number of elemnts in your list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
total=0
for i in range(n):
total+=n
mean=total/n
total=0
for i in range(n):
total+=(i-mean)**2
var=total/n
SD=sqrt(var)
print('Mean=',mean)
print('Variance=',var)
print('Standard Deviation=',SD)

Output:
Enter the number of elemnts in your list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3

Nisha S K, Assistant Professor, SVIT Page 53


Python Programming-21EC643

Enter the value: 4


Enter the value: 5
Mean= 5.0
Variance= 11.0
Standard Deviation= 3.3166247903554

Create a DB using dictionaries containing key as USN and related


fields containing Name, gender, Marks1, Marks2 & Marks3 of students.
Implement the following functions to perform i) Update
Name/gender/marks ii) search for usn and display the relevant fields iii)
delete based on search for name iv)generate the report with avg marks
more than 70%

student_db = {}

def add_student(usn, name, gender, marks1, marks2, marks3):


student_db[usn] = {
"Name": name,
"Gender": gender,
"Marks1": marks1,
"Marks2": marks2,
"Marks3": marks3
}

def update_student(usn, name=None, gender=None, marks1=None,


marks2=None, marks3=None):
if usn in student_db:
if name:
student_db[usn]["Name"] = name
if gender:
student_db[usn]["Gender"] = gender
if marks1 is not None:
student_db[usn]["Marks1"] = marks1
if marks2 is not None:
student_db[usn]["Marks2"] = marks2
if marks3 is not None:
student_db[usn]["Marks3"] = marks3
else:

Nisha S K, Assistant Professor, SVIT Page 54


Python Programming-21EC643

print("Student with USN", usn, "not found.")

def search_student_by_usn(usn):
return student_db.get(usn, "Student not found.")

def delete_student_by_name(name):
usns_to_delete = [usn for usn, details in student_db.items() if details["Name"]
== name]
for usn in usns_to_delete:
del student_db[usn]

def generate_report():
report = {}
for usn, details in student_db.items():
avg_marks = (details["Marks1"] + details["Marks2"] + details["Marks3"]) / 3
if avg_marks > 70:
report[usn] = details
return report

def main():
while True:
print("\nStudent Database Menu:")
print("1. Add Student")
print("2. Update Student")
print("3. Search Student by USN")
print("4. Delete Student by Name")
print("5. Generate Report (Avg Marks > 70%)")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
usn = input("Enter USN: ")
name = input("Enter Name: ")
gender = input("Enter Gender: ")
marks1 = float(input("Enter Marks1: "))
marks2 = float(input("Enter Marks2: "))
marks3 = float(input("Enter Marks3: "))
add_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student {name} added successfully.")

Nisha S K, Assistant Professor, SVIT Page 55


Python Programming-21EC643

elif choice == '2':


usn = input("Enter USN to update: ")
name = input("Enter new Name (leave blank to skip): ") or None
gender = input("Enter new Gender (leave blank to skip): ") or None
marks1 = input("Enter new Marks1 (leave blank to skip): ")
marks2 = input("Enter new Marks2 (leave blank to skip): ")
marks3 = input("Enter new Marks3 (leave blank to skip): ")
marks1 = float(marks1) if marks1 else None
marks2 = float(marks2) if marks2 else None
marks3 = float(marks3) if marks3 else None
update_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student with USN {usn} updated successfully.")
elif choice == '3':
usn = input("Enter USN to search: ")
result = search_student_by_usn(usn)
print("Search Result:", result)
elif choice == '4':
name = input("Enter Name to delete: ")
delete_student_by_name(name)
print(f"Student(s) with name {name} deleted successfully.")
elif choice == '5':
report = generate_report()
print("Report of students with average marks > 70%:")
for usn, details in report.items():
print(f"USN: {usn}, Details: {details}")
elif choice == '6':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Write a program to enter names of employees and their salaries as input and
store them in a dictionary.

num = int(input("Enter the number of employees whose data to be stored: "))

Nisha S K, Assistant Professor, SVIT Page 56


Python Programming-21EC643

count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])

Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000

****End****

Nisha S K, Assistant Professor, SVIT Page 57


Python Programming-21EC643

Module 2

Manipulating Strings

Write a program with a user defined function to count the


number of times a character (passed as argument) occurs in the
given string.

def charCount(ch,st):
count = 0
for character in st:
if character == ch: count += 1
return count #end of function

st = input("Enter a string: ")


ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)

Output:

Enter a string: Hello World


Enter the character to be searched: o
Number of times character o occurs in the string is: 2

Write a program with a user defined function with string as a


parameter which replaces all vowels in the string with '*'.

def replaceVowel(st):
newstr=''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
st1 = replaceVowel(st)

Nisha S K, Assistant Professor, SVIT Page 1


Python Programming-21EC643

print("The original String is:",st)


print("The modified String is:",st1)

Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld

Write a program to input a string from the user and print it in


the reverse order without creating a new string.

st = input("Enter a string: ")


for i in range(-1,-len(st)-1,-1):
print(st[i],end='')

Output:
Enter a string: Hello World
dlroW olleH

Write a program which reverses a string passed as parameter


and stores the reversed string in a new string. Use a user
defined function for reversing the string.

def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr #end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)
Output:
Enter a String: Hello World
The original String is: Hello World

Nisha S K, Assistant Professor, SVIT Page 2


Python Programming-21EC643

The reversed String is: dlroW olleH

Write a program using a user defined function to check if a string is a


palindrome or not.

def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True #end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")

Output 1:
Enter a String: madam
The given string madam is a palindrome
Output 2:
Enter a String: Computer
The given string Computer is not a palindrome

Nisha S K, Assistant Professor, SVIT Page 3

You might also like