Unit 4
Unit 4
Unit IV
4.1 LISTS
List is an ordered sequence of items. Values in the list are called elements /
items. It can be written as a list of comma-separated items (values) between square
brackets [ ]. Items in the lists can be of different data types.
Example:
ps = [10, 20, 30, 40]
qs = [“spam”, “bungee”, “swallow”]
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don t have to be the same type. The following list contains a
string, a float, an integer, and another list: zs = [“hello”, 2.0, 5, [10, 20]]
A list within another list is said to be nested. Finally, a list with no elements is
called an empty list, and is denoted [].
A list of Integers : [1951,1952,1953,1958,1957]
A list of Strings : [„orange , blue , yellow ]
An empty list : []
4.2 Problem Solving and Python Programming
4.1.1 List Operations:
Operations Examples Description
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create alist
>>> print(a) at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the item in the
2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last elementusing
10 negative indexing.
Slicing >>> print(a[0:3]) Printing a part of the list.
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Concatenation >>>b=[20,30] Adding and printing theitems of
>>> print(a+b) two lists.q
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Repetition >>> print(b*3) Create a multiple copies ofthe
[20, 30, 20, 30, 20, 30] same list.
Updating >>> print(a[2]) Updating the list using index
4>>> a[2]=100 value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element ispresent
>>> 5 in a in list. Otherwisereturns false.
True
>>> 100 in a
False
>>> 2 not in a
False
Comparison >>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elementsin both
>>>b=[2,3,4] elements are same.Otherwise
>>> a==b returns false
False
>>> a!=b
True
LIsts, Tuples, Dictionaries 4.3
append():
Example 1:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.append(‘goat’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, ‘goat’]
4.6 Problem Solving and Python Programming
Example 2:
animal = [‘cat’, ‘dog’, ‘rabbit’]
wild_animal = [‘tiger’, ‘fox’]
animal.append(wild_animal)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, [‘tiger’, ‘fox’]]
insert():
Example:
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
vowel.insert(3, ‘o’)
print(‘Updated List: ‘, vowel)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
extend():
Example:
language = [‘French’, ‘English’, ‘German’]
language1 = [‘Spanish’, ‘Portuguese’]
language.extend(language1)
print(‘Language List: ‘, language)
Output:
Language List: [‘French’, ‘English’, ‘German’, ‘Spanish’, ‘Portuguese’]
Index():
Example 1:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]
index = vowels.index(‘e’)
print(‘The index of e:’, index)
index = vowels.index(‘i’)
print(‘The index of i:’, index)
LIsts, Tuples, Dictionaries 4.7
Output:
The index of e: 1
The index of e: 2
Example 2:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
index = vowels.index(‘p’)
print(‘The index of p:’, index)
Output:
ValueError: ‘p’ is not in list
remove():
Example:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.remove(‘rabbit’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’]
clear():
Example:
list = [{1, 2}, (‘a’), [‘1.1’, ‘2.2’]]
list.clear()
print(‘List:’, list)
Output: List: []
Sort():
Example 1:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort()
print(‘Sorted list:’, vowels)
4.8 Problem Solving and Python Programming
Output:
Sorted list: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 2:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort(reverse=True)
print(‘Sorted list (in Descending):’, vowels)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
reverse():
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
os.reverse()
print(‘Updated List:’, os)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
reversed_list = os[::-1]
print(‘Updated List:’, reversed_list)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Pop():
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
LIsts, Tuples, Dictionaries 4.9
return_value = language.pop(3)
print(‘Return Value: ‘, return_value)
print(‘Updated List: ‘, language)
Output:
Return Value: French
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘C’]
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘Ruby’, ‘C’]
print(‘When index is not passed:’)
print(‘Return Value: ‘, language.pop())
print(‘Updated List: ‘, language)
print(‘\nWhen -1 is passed:’)
print(‘Return Value: ‘, language.pop(-1))
print(‘Updated List: ‘, language)
print(‘\nWhen -3 is passed:’)
print(‘Return Value: ‘, language.pop(-3))
print(‘Updated List: ‘, language)
Output:
When index is not passed:
Return Value: C
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘Ruby’]
When -1 is passed:
Return Value: Ruby
Updated List: [‘Python’, ‘Java’, ‘C++’]
When -3 is passed:
Return Value: Python
Updated List: [‘Java’, ‘C++’]
4.10 Problem Solving and Python Programming
4.1.4 List loop
Python’s for statement provides a convenient means of iterating over lists.
For loop:
A for statement is an iterative control statement that iterates once for each element
in a specified sequence of elements. Thus, for loops are used to construct definite
loops.
Syntax:
for val in sequence:
Example1:
a=[10,20,30,40,50]
for i in a:
print(i)
Output :
1
2
3
4
5
Example 2 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
Output :
0
1
2
3
4
LIsts, Tuples, Dictionaries 4.11
Example 3 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
Output ;
10
20
30
40
50
While loop:
The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.When the condition is tested and the result is false,
the loop body will be skipped and the first statement after the while loop will be
executed.
Syntax:
while (condition):
body of while
Example : Sum of Elements in a List
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
print (b)
a is b
b[2]=35 10 20 30 40
a
print(a) a = [10, 20, 30]
print(b) 0 1 2 3
Output :
[10,20,30,40] b
True
0 1 2 3
[10,20,30,40]
b = [10, 20, 30] 10 20 30 40
[10,20,35,40] a
0 1 2 3
0 1 2 3
b [2] = 35
10 20 30 40
a
0 1 2 3
In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced. This type of change is what is known as a side effect. This
happens because after the assignment b=a, the variables a and b refer to the exact
same list object.
They are aliases for the same object. This phenomenon is known as aliasing. To
prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.
4.2 TUPLES
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a
tuple is defined, it cannot be altered. Otherwise, tuples and lists are essentially the
same. To distinguish tuples from lists, tuples are denoted by parentheses instead of
square brackets.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be
used.
Tuples can be used as keys in dictionaries, while lists can’t.
An empty tuple is represented by a set of empty parentheses, ().The elements
of tuples are accessed the same as lists, with square brackets, Any attempt to alter a
tuple is invalid. Thus, delete, update, insert, and append operations are not defined
on tuples.
LIsts, Tuples, Dictionaries 4.17
max(tuple)
>>> max(a)
5
del(tuple)
>>> del(a)
4.3 DICTIONARIES
A dictionary organizes information by association, not position.
Example: when you use a dictionary to look up the definition of “mammal,”
you don t start at page 1; instead, you turn directly to the words beginning with “M.”
Phone books, address books, encyclopedias, and other reference sources also organize
information by association. In Python, a dictionary associates a set of keys with data
values. A Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries is
enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Note : Elements in Dictionaries are accessed via keys and not by their position.
Here are some example dictionaries:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:
dict[‘Name’]: Zara
dict[‘Age’]: 7
4.22 Problem Solving and Python Programming
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error. We can even create an empty dictionary—that is, a dictionary that
contains no entries. We would create an empty dictionary in a program that builds a
dictionary from scratch.
Membership
a={1: ‘ONE’, 2: ‘two’, 3: ‘three’}
>>> 1 in a
True
>>> 3 not in a
False
Example 2 :
>>>[x for x in range(1,10) if x%2==0]
Output :
[2, 4, 6, 8]
Example 3 :
>>>[x+3 for x in [1,2,3]]
Output :
[4, 5, 6]
Example 4 :
>>> [x*x for x in range(5)]
Output :
[0, 1, 4, 9, 16]
2. Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
4.26 Problem Solving and Python Programming
Reference Links :
List :
NPTEL : https://www.youtube.com/watch?time_continue=4&v=0y5HOotxpys
https://www.youtube.com/watch?v=ffMgNo17Ork
Youtube : https://www.youtube.com/watch?v=ohCDWZgNIU0
Tuples
NPTEL : https://www.youtube.com/watch?time_continue=6&v=lR8DWx2fcbQ
Youtube : https://www.youtube.com/watch?v=vQItTnigtrg
Courseera : https://www.coursera.org/lecture/python-for-applied-data-science/
list-and-tuples-bUWEy
Dictionaries:
NPTEL : https://www.youtube.com/watch?time_continue=1&v=lR8DWx2fcbQ
Youtube : https://www.youtube.com/watch?v=V8CQkDTt7eA
ILLUSTRATIVE PROGRAMS
1. Program for matrix addition
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
2. Program for matrix subtraction
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
for r in result:
print(r)
3. Program for matrix Multiplication
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
4.28 Problem Solving and Python Programming
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
4. Program for Selection Sort
Selection sort is one of the simplest sorting algorithms. It is similar to the hand
picking where we take the smallest element and put it in the first position and the
second smallest at the second position and so on.
We first check for smallest element in the list and swap it with the first element
of the list. Again, we check for the smallest number in a sublist, excluding the first
element of the list as it is where it should be (at the first position) and put it in the
second position of the list. We continue repeating this process until the list gets sorted.
LIsts, Tuples, Dictionaries 4.29
23 78 45 8 32 56 Original list
Unsorted
8 78 45 23 32 56 After pass 1
Unsorted
8 23 45 78 32 56 56 After pass 2
Unsorted
8 23 32 78 45 56 After pass 3
Sorted Unsorted
8 23 32 45 78 56 After pass 4
Sorted
8 23 32 45 56 78 After pass 5
Sorted
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
1 3 1 5 2 9 5 4
1 5 4 5
1 4 5 4 5 6
1 1 3 4 5 2 4 5 6 9
1 1 2 3 4 4 5 5 6 9
Python Code
def mergeSort(nlist):
print(“Splitting “,nlist)
if len(nlist)>1:
mid = len(nlist)//2
LIsts, Tuples, Dictionaries 4.33
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
def mergeSort(nlist)
print(”Splitting”, nlist)
len(nlist)>1?
Yes
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
Yes No No
lefthalf[i] <
i < len(lefthalf) ?
righthalf[j]?
Yes No Yes No
Yes No
nlist[k] = righthalf[j]
K=K+1 j=j+1 print(”Merging”, nlist)
k=k+1
End
LIsts, Tuples, Dictionaries 4.35
PRACTICE PROBLEMS
1. Write a python Program to calculate the average of numbers in a list
2. Write a python Program to find the maximum and minimum number in a list
3. Write a python Program to list even and odd numbers of a list
4. Write a Python program
i. To add new elements to the end of the list
ii. To reverse elements in the list
iii. To display same list elements multiple times.
iv. To concatenate two list.
v. To sort the elements in the list in ascending order.
5. Write a Python program for cloning the list and aliasing the list.
6. Write a Python program: “tuple1 = (10,50,20,40,30)”
i. To display the elements 10 and 50 from tuple1
ii. To display length of a tuple1.
iii. To find the minimum element from tuple1.
iv. To add all elements in the tuple1.
v. To display same tuple1 multiple times
LIsts, Tuples, Dictionaries 4.37
ASSIGNMENT QUESTIONS
1. With a given integral number n, write a program to generate a dictionary that
contains (i, i*i) such that is an integral number between 1 and n (both included).
and then the program should print the dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hints:
In case of input data being supplied to the question, it should be assumed to be a
console input.
Consider use dict()
2. Define a function which can print a dictionary where the keys are numbers
between 1 and 3 (both included) and the values are square of keys.
4.38 Problem Solving and Python Programming
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
3. Define a function which can print a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
4. Define a function which can generate and print a list where the values are square
of numbers between 1 and 20 (both included).
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
5. With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half
values in one line and the last half values in one line.
Hints: Use [n1:n2] notation to get a slice from a tuple.
6. By using list comprehension, please write a program to print the list after
removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
7. With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print
this list after removing all duplicate values with original order reserved.
Hints:
Use set() to store a number of values without duplicate.
LIsts, Tuples, Dictionaries 4.39
8. Define the variables x and y as lists of numbers, and z as a tuple.
x=[1, 2, 3, 4, 5]
y=[11, 12, 13, 14, 15]
z=(21, 22, 23, 24, 25)
(a) What is the value of 3*x?
(b) What is the value of x+y?
(c) What is the value of x-y?
(d) What is the value of x[1]?
(e) What is the value of x[0]?
(f) What is the value of x[-1]?
(g) What is the value of x[:]?
(h) What is the value of x[2:4]?
(i) What is the value of x[1:4:2]?
(j) What is the value of x[:2]?
(k) What is the value of x[::2]?
(l) What is the result of the following two expressions?
x[3]=8
print x
(m) What is the result of the above pair of expressions if the list x were
replaced with the tuple z?
9. An assignment statement containing the expression a[m:n] on the left side and a
list on the right side can modify list a. Complete the following table by supplying
the m and n values in the slice assignment statement needed to produce the
indicated list from the given original list.
Original List Target List Slice indices
m n
[2, 4, 6, 8 , 10] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[2, 4, 6, 8 , 10] [–10, –8, –6, –4, –2, 0, 2, 4, 6, 8, 10]
[2, 4, 6, 8 , 10] [2, 3, 4, 5, 6, 7, 8, 10]
[2, 4, 6, 8 , 10] [2, 4, 6, ‘a’, ‘b’, ‘c’, 8, 10]
[2, 4, 6, 8 , 10] [2, 4, 6, 8, 10]
[2, 4, 6, 8 , 10] []
[2, 4, 6, 8 , 10] [10, 8, 6, 4, 2]
[2, 4, 6, 8 , 10] [2, 4, 6]
[2, 4, 6, 8 , 10] [6, 8, 10]
[2, 4, 6, 8 , 10] [2, 10]
[2, 4, 6, 8 , 10] [4, 6, 8]
4.40 Problem Solving and Python Programming
PART A QUESTION AND ANSWERS
1. Define python list.
The list is written as a sequence of data values separated by commas. There are
several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]): ps = [10, 20, 30, 40]
2. Write the different ways to create the list.
List1=[4,5,6].
List2=[]
List2[0]=4
List2[1]=5
List2[2]=6
3. Give an example for nest list
A list within the another list is called as nested list.
Eg: zs = [“hello”, 2.0, 5, [10, 20]]
4. Write the syntax for accessing the list elements.
The way to access list elements is index operator.
Eg: List1=[4,5,6]
List1[0]=4
List1[1]=5
List1[2]=6
5. List out the methods used in list.
Append, Extend, Insert, Index, sort, reverse, pop, remove, clear
6. Write a python program for reversing a list.
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’] vowels.sort(reverse=True)
print(‘Sorted list (in Descending):’, vowels)
7. Write a python program to add a single element to the end of the list.
vowels = [‘e’, ‘a’, ‘u’, ‘i’]
vowels.append(‘o’)
LIsts, Tuples, Dictionaries 4.41
8. Write a python program to print the list elements using for loop.
num=[10,22,33,44,50,66]
for k in num: print (k)
9. Is list is mutable? Justify your answer.
List elements can be changed once after initializing the list. This is called as
mutability.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers[42, 5]
10. Write difference between list aliasing and cloning.
An object with more than one reference has more than one name, the object is
aliased. If the aliased object is mutable, changes made with one alias affect the
other. Clone changes are not being affected the other copy of list.
11. How tuple is differ from list?
Tuples are created by using ( ).
Tuples are immutable.
List is created by using [ ].
List is mutable.
12. Explain how tuples are used as return values
A function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values.
>>> t = divmod(7, 3)
>>> t (2,1)
13. What is a dictionary? Give an example.
Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries
is enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Eg: dict = {‘Name’: ‘Zara’, ‘Age’: 7}
4.42 Problem Solving and Python Programming
14. List out the methods used in dictionary.
Get, fromkeys, clear, copy, items, pop,popitem, setdefault, update, etc. How do
we done the membership test in dictionary?
>>>C={1:1,2:2}
>>>2 in C True
15. Write a python program for iterating the dictionary elements.
squares = {1: 1, 3: 9, 5: 25, 7: 49}
for i in squares: print(squares[i])
16. What is called entries in dictionary?
Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries.
17. List out the built in functions of dictionary.
The functions in dictionary : len( ), any( ), all( ), comp( ), sorted( )
PART B QUESTIONS
1. Discuss about tuple in detail.
2. Define list. Mention the list operations with programs.
3. Explain about advanced list processing and list comprehension.
4. Discuss about Dictionaries, its operations and methods.
5. Code programs :
a. Insertion sort
b. Selection sort
c. Merge sort
d. Histogram