0% found this document useful (0 votes)
5 views42 pages

Unit 4

This document provides an overview of lists, tuples, and dictionaries in Python, detailing their operations, methods, and examples. It covers list creation, indexing, slicing, and various list methods such as append, insert, and sort. Additionally, it discusses the mutability of lists and includes illustrative programs for sorting algorithms.

Uploaded by

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

Unit 4

This document provides an overview of lists, tuples, and dictionaries in Python, detailing their operations, methods, and examples. It covers list creation, indexing, slicing, and various list methods such as append, insert, and sort. Additionally, it discusses the mutability of lists and includes illustrative programs for sorting algorithms.

Uploaded by

vlpmfamily936
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

LIsts, Tuples, Dictionaries 4.

Unit IV

LISTS, TUPLES, DICTIONARIES


Lists: list operations, list slices, list methods, list loop, mutability,
aliasing, cloning lists, list parameters; Tuples: tuple assignment, tuple
as return value; Dictionaries: operations and methods; advanced list
processing - list comprehension; Illustrative programs: selection sort,
insertion sort, merge sort, histogram.

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

4.1.2 List Slicing


The slice operation uses the square brackets. This is termed indexing, or slicing.
An index or slice returns a portion of a larger value. In a string this can be used to
produce a substring. Index values start at zero, and extend upwards to the number of
characters in the string minus one. When a single argument is given it is one character
out of the string. When two integers are written, separated by a colon, it is termed a
slice. The second value is an ending position. A portion of the string starting at the
given position up to but not including the ending position is produced.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
Example :
Slices Example Description
a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from 0 to 2.
>>> a[0:3]
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. soprints from 0
[9, 8, 7, 6] to 3
a[1:] >>> a[1:] default stop value will ben-1. so prints
[8, 7, 6, 5, 4] from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]
a[2:2] >>> a[2:2] print an empty slice
[]
a[0:6:2] >>> a[0:6:2] Slicing list values with stepsize 2.
[9, 7, 5]
a[::-1] >>> a[::-1] Returns reverse of given listvalues
[4, 5, 6, 7, 8, 9]
4.4 Problem Solving and Python Programming
4.1.3 List Methods
Methods used in lists are used to manipulate the data quickly. These methods
work only on lists. They do not work on the other sequence types that are not mutable,
that is, the values they contain cannot be changed, added, or deleted.
Syntax:
List_name.method_name( element/index/list)
syntax example description
a.append(element) >>> a=[1,2,3,4,5] Add an element to the end of the
>>> a.append(6) list
>>> print(a)
[1, 2, 3, 4, 5, 6]
a.insert(index,element) >>> a.insert(0,0) Insert an item at the defined
>>> print(a) index
[0, 1, 2, 3, 4, 5, 6]
a.extend(b) >>> b=[7,8,9] Add all elements of a list to the
>>> a.extend(b) another list
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
a.index(element) >>> a.index(8) Returns the index of the first
8 matched item
a.sort() >>> a.sort() Sort items in a list in ascending
>>> print(a) order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
a.reverse() >>> a.reverse() Reverse the order of items in the
>>> print(a) list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop() >>> a.pop() Remo ves and ret urns an
0 element at the last element
a.pop(index) >>> a.pop(0) Remove the particular element
8 and return it.
LIsts, Tuples, Dictionaries 4.5

a.remove(element) >>> a.remove(1) Removes an item from the list


>>> print(a)
[7, 6, 5, 4, 3, 2]
a.count(element) >>> a.count(6) Returns the count of number of
1 items passed as an argument
a.copy() >>> b=a.copy() Returns a shallow copy of the
>>> print(b) list
[7, 6, 5, 4, 3, 2]
len(list) >>> len(a) Return the length of the length
6

min(list) >>> min(a) Return the minimum element in


2 a list
max(list) >>> max(a) Return the maximum element in
7 a list.

a.clear() >>> a.clear() Removes all items from the list.


>>> print(a)
[]

del(a) >>> del(a) Delete the entire list.


>>> print(a)
Error: name ‘a’ is not
defined

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)

4.1.5 List Mutability


Lists are mutable. When the bracket operator appears on the left side of an
assignment, it Identifies the element of the list that will be assigned.
4.12 Problem Solving and Python Programming
Example:
Changing Single Element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
Changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
The elements from a list can also be removed by assigning the empty list to
them.
>>> a=[1,2,3,4,5]
>>> a[0:3]=[ ]
>>> print(a)
[4, 5]
The elements can be inserted into a list by squeezing them into an empty
slice at the desired location.
>>> a=[1,2,3,4,5]
>>> a[0:0]=[20,30,45]
>>> print(a)
[20,30,45,1, 2, 3, 4, 5]

4.1.6 List Aliasing


Creating a copy of a list is called aliasing. When you create a copy both list will
be having same memory location. Changes in one list will affect another list. Aliasing
refers to having different names for same list values.
Example :
a= [10,20,30,40]
b=a
LIsts, Tuples, Dictionaries 4.13

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.1.7 List Cloning


To avoid the disadvantages of copying we are using cloning. Creating a copy of
a same list of elements with two different memory locations is called cloning. Changes
in one list will not affect locations of another list.
4.14 Problem Solving and Python Programming
Cloning is a process of making a copy of the list without modifying the original
list.
1. Slicing
2. list()method
3. copy() method
Cloning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
Cloning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
Cloning using copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b) [1, 2, 3, 4, 5]
>>> a is b
False
LIsts, Tuples, Dictionaries 4.15

4.1.8 List Parameters


In python, arguments are passed by reference. If any changes are done in the
parameter which refers within the function, then the changes also reflects back in the
calling function. When a list to a function is passed, the function gets a reference to
the list.
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. Since lists are mutable, changes made to the elements referenced by the
parameter change the same list that the argument is referencing.
Example1 :
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output:
[2,3,4,5]
Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Output
inside [11, 12, 13, 14, 15]
outside [11, 12, 13, 14, 15]
Example 3
def insert(a):
a.insert(0,30)
4.16 Problem Solving and Python Programming
a=[1,2,3,4,5]
insert(a)
print(a)
Output
[30, 1, 2, 3, 4, 5]
Suggested links to Refer :
List :
https://www.tutorialspoint.com/videotutorials/
video_course_view.php?course=python_online_training&chapter=python_basic_list_operation
List Using for Loop:
https://www.youtube.com/watch?v=YT6ldZuBW4Y
Python List functions:
https://www.youtube.com/watch?v=96Wr1OO-4d8
Python Slicing:
https://www.youtube.com/watch?v=iD6a0G8MnjA

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

4.2.1 Operations on Tuples


1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Creating a tuple
>>>a=(20,40,60,”apple”,”ball”)
Indexing
>>>print(a[0])
20
>>> a[2]
60
Slicing
>>>print(a[1:3])
(40,60)
Concatenation
>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”apple”,”ball”,2,4)
Repetition
>>>print(b*2)
>>>(2,4,2,4)
Membership
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
4.18 Problem Solving and Python Programming
>>> 100 in a
False
>>> 2 not in a
False
Comparison
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
>>> a!=b
True

4.2.2 Tuple methods


Tuple is immutable so changes cannot be done on the elements of a tuple once it
is assigned.
a.index(tuple)
>>> a=(1,2,3,4,5)
>>> a.index(5)
4
a.count(tuple)
>>>a=(1,2,3,4,5)
>>> a.count(3)
1
len(tuple)
>>> len(a)
5
min(tuple)
>>> min(a)
1
LIsts, Tuples, Dictionaries 4.19

max(tuple)
>>> max(a)
5
del(tuple)
>>> del(a)

4.2.3 Tuple Assignment


Tuple assignment allows variables on the left of an assignment operator and
values of tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each expression to a
target.Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable:
a=20
b=50
temp = a
a=b
b = temp
print(“value after swapping is”,a,b)
Swapping using tuple assignment:
a=20
b=50
(a,b)=(b,a)
print(“value after swapping is”,a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
4.20 Problem Solving and Python Programming
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

4.2.4 Tuple as return value


A Tuple is a comma separated sequence of items. It is created with or
without ( ). A function can return one value. if you want to return more than one value
from a function. We can use tuple as return value.
Example :
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input(“enter a value:”))
b=eval(input(“enter b value:”))
r,q=div(a,b)
print(“reminder:”,r)
print(“quotient:”,q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print(“smallest:”,small)
print(“biggest:”,big)
LIsts, Tuples, Dictionaries 4.21

4.2.5 Tuple as argument


The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,’a’)
Output :
(2, 3, ‘a’)
Suggested Links to Refer
Tuples : https://www.youtube.com/watch?v=R8mOaSIHT8U
Tuple as Paramerter : https://www.youtube.com/watch?v=sgnP62EXUtA
Tuple assignment : https://www.youtube.com/watch?v=AhSW1sEOzWY

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.

4.3.1 Dictionary Operations


Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Creating a dictionary
>>> a={1:”one”,2:”two”}
>>> print(a)
{1: ‘one’, 2: ‘two’}
Accessing an element
>>> a[1]
‘one’
>>> a[0]
KeyError: 0
Update
>>> a[1]=”ONE”
>>> print(a)
{1: ‘ONE’, 2: ‘two’}
Add element
>>> a[3]=”three”
>>> print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’}
LIsts, Tuples, Dictionaries 4.23

Membership
a={1: ‘ONE’, 2: ‘two’, 3: ‘three’}
>>> 1 in a
True
>>> 3 not in a
False

4.3.2 Dictionary Methods


Method Example Description
a.copy() a={l: ‘ONE’. 2: ‘two’. 3: ‘three’} It ret u rns co py o f t he
>>> b=a.copy() dictionary, here copy of
>>> print(b) dictionary ‘a’ get stored in
{1: ‘ONE’, 2: ‘two’. 3: ‘three’} to dictionary ‘b’

a.items() >>> a.items() Return a new view of the


diet_items([(l, ‘ONE’). (2. ‘two’). dict io nary’s it ems. It
(3. ‘three’)]) displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >> a.keys() It displays list of keys in a
diet keys([1, 2,]) dictionary
a.values() >>> a.values() It displays list of values in
diet_valuesf ([‘ONE’. ‘two’, ‘three’]) dictionary
a.pop(key) >>> a.pop(3) Remove the element with
‘three’ key and return its value
>>> print(a) from the dictionary.
{1: ‘ONE’. 2: ‘two’}
setdefault >>> a.setdefault(3,“three”) If key is in the dictionary,
(key.value) ‘three’ return its value. If key is not
>>> print(a) present, insert key with a
{1: ‘ONE’. 2: ‘two’, 3: ‘three’} value o f dict io nary and
>>> a.setdefault(2) return dictionary.
‘two’
4.24 Problem Solving and Python Programming

a.update >>> b={4:”four”} It will add the dictionary


(dictionary) >>> a.update(b) with the existing dictionary
>>> print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
fromkeys() >>> key={“apple”.”ball”} It creates a dictionary from
>>> value=“for kids” key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{‘apple’: ‘for kids’, ‘ball’: ‘for kids’}
len(a) a={l: ‘ONE’, 2: ‘two’, 3: ‘three’} It returns the length of the
>>>lena(a) list
3
clear() a={1: ‘ONE’, 2: ‘two’. 3: ‘three’} Remove all elements form
>>>a.clear() the dictionary.
>>>print(a)
>>>{}
del(a) a={l: ‘ONE’, 2: ‘two’. 3: ‘three’} It will delete the entire
>>> del(a) dictionary.
4.4 ADVANCED LIST PROCESSING
1. List Comprehension:
List comprehensions provide a concise way to apply operations on a list. It creates
a new list in which each element is the result of applying a given operation in a list. It
consists of brackets containing an expression followed by a “for” clause, then a list.
The list comprehension always returns a result list.
Syntax:
list=[ expression for item in list if conditional ]
Example 1:
>>>L=[x**2 for x in range(0,5)]
>>>print(L)
Output :
[0, 1, 4, 9, 16]
LIsts, Tuples, Dictionaries 4.25

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

# iterate through rows


for i in range(len(X)):
LIsts, Tuples, Dictionaries 4.27

# 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)
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

Working of selection sort:

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

Let’s code this in Python


a = [23,78,45,8,32,56]
i=0
while i<len(a):
#smallest element in the sublist
smallest = min(a[i:])
#index of smallest element
index_of_smallest = a.index(smallest)
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print (a)
4.30 Problem Solving and Python Programming
Output
[ 8,23,32,45,56,78 ]
5. Program for insertion sort
Insertion sort is similar to arranging the documents of a bunch of students in
order of their ascending roll number. Starting from the second element, we compare it
with the first element and swap it if it is not in order. Similarly, we take the third
element in the next iteration and place it at the right place in the sublist of the first and
second elements (as the sublist containing the first and second elements is already
sorted). We repeat this step with the fourth element of the list in the next iteration and
place it at the right position in the sublist containing the first, second and the third
elements. We repeat this process until our list gets sorted.
LIsts, Tuples, Dictionaries 4.31

Let us code this in python


a = [12,3,1,5,8]
#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output :
[ 1,3,5,8,12]
Explanation of the code
for i in a – We are iterating over the list ‘a’
while j>0 – Index of the current element is positive. This means that the element
at the index of ‘j’ is not the first element and we need to compare the values.
if a[j-1] > a[j] – These two elements are not in order. We need to swap them. else
– The elements are in order, we can break the while loop.
a[j-1],a[j] = a[j],a[j-1] – Swapping.
6. Program for merge sort
Merge sort is a divide-and-conquer algorithm based on the idea of breaking down
a list into several sub-lists until each sublist consists of a single element and merging
those sublists in a manner that results into a sorted list.
4.32 Problem Solving and Python Programming

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

while i < len(lefthalf):


nlist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


nlist[k]=righthalf[j]
j=j+1
k=k+1
print(“Merging “,nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
Output:
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Merging [14]
4.34 Problem Solving and Python Programming
Splitting [46]
———
Merging [14, 21, 27, 41, 43, 45, 46, 57, 70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]
Flowchart

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

i < len(lefthalf) and j


< len(righthalf)?

Yes No No

lefthalf[i] <
i < len(lefthalf) ?
righthalf[j]?

Yes No Yes No

nlist[k] = righthalf[1] nlist[k] = lefthalf[i]


nlist[k] = lefthalf[1] j < len(righthalf) ?
j=j+1 i=i+1
i=i+1
k=k+1

Yes No

nlist[k] = righthalf[j]
K=K+1 j=j+1 print(”Merging”, nlist)
k=k+1

End
LIsts, Tuples, Dictionaries 4.35

7. Python program for printing histogram


Write a Python program to create a histogram from a given list of integers.
def histogram( items ):
for n in items:
output = ‘’
times = n
while( times > 0 ):
output += ‘*’
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Output:
**
***
******
*****
8. Python program to print the calendar of the month
import calendar
y=int(input(“enter year:”))
m=int(input(“enter month:”))
print(calendar.month(y,m))
Output:
enter year: 2018
enter month: 8
August 2018
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
4.36 Problem Solving and Python Programming
Suggested Link to Refer :
Selection Sort : https://www.youtube.com/watch?v=mI3KgJy_d7Y
Insertion Sort : https://www.youtube.com/watch?v=Nkw6Jg_Gi4w
Quick Sort(NPTEL) : https://youtu.be/zjqzrcljMlI
Merge Sort (NPTEL) : https://youtu.be/V7fvTmhqokM
Reference:
htt p://int eract ivepyt hon.o rg/co urselib/static/pyt ho nds/Sort Search/
TheMergeSort.html

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

7. Write a Python program


i. To create a dictionary
ii. To adding an element to dictionary
iii. To display length of the dictionary.
iv. To updating element in dictionary.
v. To remove all elements from the dictionary.
8. Write a python program to accept ‘n’ names, sort names in alphabetic order and
print the result.
9. Write a python program to store ‘n’ names in a list and sort the list using
selection sort.
10. Write a python program to merge two lists.
11. Write a python program to remove duplicates from a list.
12. Write a python program to find the 1 st and 2nd largest element in the list.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy