0% found this document useful (0 votes)
18 views20 pages

Unit_4_GE3151-PSPP

Unit IV covers Lists, Tuples, and Dictionaries in Python, detailing their operations, methods, and differences. It explains list operations such as indexing, slicing, and mutability, as well as tuple assignment and dictionary key-value pairs. The unit also includes illustrative programs for retail bill preparation, student mark systems, histograms, and sorting algorithms.
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)
18 views20 pages

Unit_4_GE3151-PSPP

Unit IV covers Lists, Tuples, and Dictionaries in Python, detailing their operations, methods, and differences. It explains list operations such as indexing, slicing, and mutability, as well as tuple assignment and dictionary key-value pairs. The unit also includes illustrative programs for retail bill preparation, student mark systems, histograms, and sorting algorithms.
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/ 20

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:
simple sorting, histogram, Students marks statement, Retail bill preparation.

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.

1.1 Operations on list:


1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
1.2 List slices
List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.

Syntax
Listname[start:stop]
Listname[start:stop:steps]

 Default start value is 0


 Default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice
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

Listname.methodname( element/index/list)
1.4 List loops
1. For loop
2. While loop
3. Infinite loop

List using For Loop


 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using indentation.
Syntax
for val in sequence:

List using 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
Sum of elements in a list Output
a=[1,2,3,4,5] 15
i=0
summ=0
while(i<len(a)):
summ=summ+a[i]
i=i+1
print(summ)
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

1.5 Mutability
 Lists are mutable. (can be changed)
 Mutability is the ability for certain types of data to be changed without entirely
recreating it.
 An item can be changed in a list by accessing it directly as part of the assignment
statement.
 Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.

1.6 Aliasing(copying)
 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.
 Alaising refers to having different names for same list values.
Example Output
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]

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

1.7 Clonning
 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.
 Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method

1. Clonning using Slicing 2. Clonning using List( ) method


>>>a=[1,2, 3,4,5] >>> a=[1,2,3,4,5]
>>>b=a[:] >>> b=list(a)
>>>print(b) >>> print(b)
[1,2,3,4,5] [1, 2, 3, 4, 5]
>>>a is b >>> a is b
False False
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> print(b)
[1, 2, 3, 4, 5]
3. Clonning using copy() method
>>> a=[1,2,3,4,5]
>>> b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False

1.8 List as 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.
Example 1 Output
def remove(a): [2, 3, 4, 5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2 Output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)

2. Tuple
 A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
 But tuple can be converted into list and list can be converted in to tuple.
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.

2.1 Operations on Tuples


1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
2.2 Tuple methods:
Tuple is immutable so changes cannot be done on the elements of a tuple once it is
assigned.

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.
Swapping using tuple assignment Output
a=20 value after swapping is 50 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.
>>> (a,b,c)=(1,2,3)
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
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 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=int(input("enter a value:"))
b=int(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)

2.5 Tuple as Argument


 The parameter name that begins with * gathers argument into a tuple.
Example Output
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')

3. Dictionaries
 Dictionary is an unordered collection of elements. An element in dictionary has a
key: value pair.
 All elements in dictionary are placed inside the curly braces i.e. { }
 Elements in Dictionaries are accessed via keys and not by their position.
 The values of a dictionary can be any data type.
 Keys must be immutable data type (numbers, strings, tuple)

3.1 Operations on Dictionary


1. Accessing an element
2. Update
3. Add element
4. Membership
3.2 Methods in dictionary
3.3 Difference between List, Tuples and dictionary:
4 Advanced list processing:
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 ]
4.1 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

5. Illustrative Program
5.1 Retail Bill Preparation

grocery_item = {}
grocery_history = []
stop = False
while not stop:
item_name = input("Item name:\n")
quantity = input("Quantity purchased:\n")
cost = input("Price per item:\n")
grocery_item = {'name':item_name, 'number': int(quantity), 'price': float(cost)}
grocery_history.append(grocery_item)
user_input = input("Would you like to enter another item?\nType 'c' for continue or 'q'
to quit:\n")
if user_input == 'q':
stop = True

grand_total = 0

for index, item in enumerate(grocery_history):


item_total = item['number'] * item['price']
grand_total = grand_total + item_total
print('%d %s at Rs%.2f each = Rs%.2f' % (item['number'], item['name'], item['price'],
item_total))
item_total = 0
print('Grand total: Rs%.2f' % grand_total)
Output
Item name:
Chocolate
Quantity purchased:
2
Price per item:
25
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
q
2 Chocolate at Rs25.00 each = Rs50.00
Grand total: Rs50.00

5.2 Student Mark System


info=int(input("Enter number of students:"))
dictionary={}
for i in range(info):
marks=[]
name=input("Enter the name of the student:")
for i in range(5):
marks.append(int(input("Enter the marks of the subject:")))
if(marks[0]<35 or marks[1]<35 or marks[2]<35 or marks[3]<35 or marks[4]<35):
status="FAIL"
else:
status="PASS"
average=sum(marks)/len(marks)
total=sum(marks)
dictionary[name]=[marks,total,average,status]

for name in dictionary:


print("******************************************")
print("Name of the Student : ",name)
print("******************************************")
print("Marks in 5 subjects : ",dictionary[name][0])
print("Total : ",dictionary[name][1])
print("Average : ",dictionary[name][2])
print("Status : ",dictionary[name][3])
Output
Enter number of students:2
Enter the name of the student: Ram
Enter the marks of the subject:12
Enter the marks of the subject:45
Enter the marks of the subject:78
Enter the marks of the subject:54
Enter the marks of the subject:43
Enter the name of the student: Ravi
Enter the marks of the subject:89
Enter the marks of the subject:67
Enter the marks of the subject:79
Enter the marks of the subject:90
Enter the marks of the subject:87
******************************************
Name of the Student : Ram
******************************************
Marks in 5 subjects : [12, 45, 78, 54, 43]
Total : 232
Average : 46.4
Status : FAIL
******************************************
Name of the Student : Ravi
******************************************
Marks in 5 subjects : [89, 67, 79, 90, 87]
Total : 412
Average : 82.4
Status : PASS

5.3 Histogram
from matplotlib import pyplot as plt
import numpy as np
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a, bins = [0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
Output

5.4 Selection Sort


print("Selection Sort")
mylist = [10,34,2,12,50,40,12]
n = len(mylist)
print("Before Sorting \n",mylist)
for i in range(0, n-1):
for j in range(i+1, n):
if (mylist[i]>mylist[j]):
temp = mylist[i]
mylist[i] = mylist[j]
mylist[j] = temp
print("After Sorting \n",mylist)

Output
Selection Sort
Before Sorting
[10, 34, 2, 12, 50, 40, 12]
After Sorting
[2, 10, 12, 12, 34, 40, 50]
5.5 Insertion Sort
print("Insertion Sort")
mylist = [10,34,2,12,50,40,17]
n = len(mylist)
print("Before Sorting \n",mylist)
for i in range(1, n):
val = mylist[i]
hole = i
while (hole>0) and (mylist[hole-1]>val):
mylist[hole] = mylist[hole-1]
hole = hole - 1
if (hole != i):
mylist[hole] = val
print("After Sorting \n",mylist)

Output
Insertion Sort
Before Sorting
[10, 34, 2, 12, 50, 40, 17]
After Sorting
[2, 10, 12, 17, 34, 40, 50]
5.6 Merge Sort
print("Merge Sort")
def mergesort(a):
n = len(a)
if (n==1):
return a
list1 = a[0: (n//2)]
list2 = a[(n//2) : n]
list1 = mergesort(list1)
list2 = mergesort(list2)
return merge(list1,list2)

def merge(a, b):


c = []
while (len(a)>0) and (len(b)>0):
if (a[0]>b[0]):
c.append(b[0])
b.pop(0)
else:
c.append(a[0])
a.pop(0)
while (len(a)>0):
c.append(a[0])
a.pop(0)
while (len(b)>0):
c.append(b[0])
b.pop(0)
return c
mylist = [14,33,27,10,35,19,42,44]
print(mylist)
print(mergesort(mylist))

Output
Merge Sort
[14, 33, 27, 10, 35, 19, 42, 44]
[10, 14, 19, 27, 33, 35, 42, 44]

You might also like