Unit 4
Unit 4
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
88
UNIT IV LISTS, TUPLES, DICTIONARIES
1. Insertion sort
Insertion sort is an elementary sorting algorithm that sorts one element at a time. Most
humans, when sorting a deck of cards, will use a strategy similar to insertion sort. The algorithm
takes an element from the list and places it in the correct location in the list. This process is repeated
until there are no more unsorted items in the list.
Example:
Program:
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Before sorting",a)
for i in range(1,n):
key=a[i]
j=i-1
while j>=0 and key<a[j]:
a[j+1]=a[j]
j-=1
a[j+1]=key
print("After sorting(using insertion sort)",a)
Output
Enter size of list6
Enter listelements4
Enter listelements33
Enter list elements6
Enter listelements22
Enter list elements6
Enter list elements-9
Before sorting [4, 33, 6, 22, 6, -9]
After sorting(using insertion sort) [-9, 4, 6, 6, 22, 33]
Government College of Engineering, Bargur
2. Selection Sort
The selection sort algorithm starts by finding the minimum value in the array and moving it to
the first position. This step is then repeated for the second lowest value, then the third, and so on until
the array is sorted.
Example
Program
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("List before sorting",a)
for i in range(0,n):
j=i+1
for j in range(j, n):
if a[i]> a[j]:
temp=a[i]
a[i]=a[j]
a[j]=temp
print("Sorted list(using Selection Sort)=",a)
Output:
Enter size of list5
Enter list elements12
Enter list elements-5
Enter list elements4
Enter listelements48
Enter listelements98
List before sorting [12, -5, 4, 48, 98]
Sorted list(using Selection Sort)= [-5, 4, 12, 48, 98]
import cmath
a = int(input("Enter the coefficients a:"))
b=int(input("Enter the coefficients b: "))
c = int(input("Enter the coefficients c: "))
d = b**2-4*a*c # discriminant
x1 = (-b+cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Output
Enter the coefficients a: 5
Enter the coefficients b: 1
Enter the coefficients c: 2
This equation has two solutions: (-0.1+0.6244997998398398j) or (-0.1-0.6244997998398398j)
4. Merge sort
Merge sort works as follows:
a. Divide the unsorted list into n sub lists, each containing 1 element (a list of 1 element is
considered sorted).
b. Repeatedly merge sub lists to produce new sorted sub lists until there is only 1 sub list
remaining. This will be the sorted list.
Example
Output
Enter size of list5
Enter list elements21
Enter list elements1
Enter list elements-8
Enter list elements14
Enter list elements18
Unsorted list is [21, 1, -8, 14, 18]
Sorted list using merge sort is [-8, 1, 14, 18, 21]
Creating a list :
The simplest way to create a new list is to enclose the elements in square brackets ([])
[10,20,30,40]
[100, "python" , 8.02]
1. LIST OPERATIONS:
1. Concatenation of list
2. Repetition of list
a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
• Here both a & b refers to the same list. Thus, any change made with one object will affect other,
since they are mutable objects.
• in general, it is safer to avoid aliasing when we are working with mutable objects
5. Cloning:
• Cloning creates a new list with same values under another name. Taking any slice of list create
new list.
• Any change made with one object will not affect others. the easiest way to clone a new list is to
use "slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]
List parameter:
• List can be passed as arguments to functions the list arguments are always passed by reference
only.
• Hence, if the functions modifies the list the caller also changes.
Eq: def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
['b','c']
In above,
The parameters 't' and the variable 'letters' or aliases for the same objects
An alternative way to write a function that creates and return a new list
Eq: def tail (t):
return t [1:]
>>> letters = ['a','b','c']
>>> result = tail (letters)
>>> result
['b','c']
In above,
The function leaves the original list unmodified and return all element in list except first element
Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by comma
t = ('a','b','c','d')
To create a tuple with a single element we have to include a final comma
>>> t = 'a',
>>> type (t)
< class 'tuple'>
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty tuple
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
>>>t= tuple('python')
>>> t
('p','y','t','h','o','n')
t = ('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)
7. Histogram
histogram([2, 3, 6, 5])
Government College of Engineering, Bargur
Two marks:
2. What is dictionary?
A dictionary is an unordered set of key: value pair. In a list, the indices have to be integers; in a
dictionary they can be any type. A dictionary contains a collection of indices, which are called keys, and
a collection of values. Each key is associated with a single value. The association of a key and a value is
called a key-value pair. Dictionary is created by enclosing with curly braces {}.
Eg:
>>>
dictionary={"RollNo":101,2:(1,2,3),"Name":"Ramesh",20:20.50,Loc":['Chennai']}
>>> dictionary
{'Name':'Ramesh', 'Loc':['Chennai'], 2:(1,2.3), 20: 20.0, 'RollNo': 101}
append() extend()
>>>a=[10,20,30] >>>a=[10,20,30]
>>>b=[40,50] >>>b=[40,50]
>>>a.append(b) >>>a.extend(b)
>>>print(a) >>>print(a)
[10,20,30,[40,50]] [10,20,30,40,50]