Unit_4_GE3151-PSPP
Unit_4_GE3151-PSPP
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.
Syntax
Listname[start:stop]
Listname[start:stop:steps]
Listname.methodname( element/index/list)
1.4 List loops
1. For loop
2. While loop
3. Infinite loop
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
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.
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)
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)
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
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
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)
Output
Merge Sort
[14, 33, 27, 10, 35, 19, 42, 44]
[10, 14, 19, 27, 33, 35, 42, 44]