Unit 4
Unit 4
Ex: [10,20,30,40]
EX:[1,2,3,1,2,3,1,2,3,]
Ex : >>>X=[10,20,30]
>>>Y=X
>>>Y is X True
5. What is tuple?
Tuple is a sequence of value. It is similar to list but there is difference
between tuple and list
Ex : T1=(10,20,30,40)
Tuple list
Tuple use parentheses() List use square bracket[]
Tuple cannot be change List can be changed
7. How can we pass variable number of argument to tuple?
The python, it is possible to have nt variable number of argument.In that
case the perameter name bigius with *. The variable number of
argument are gather into a type
Ex : def student_info(*args):
print(args)
8. What is dictionary ?
In python, dictionary is unordered collection of items. Then items are in
the form of key.value pair
The dictionary conection the collection of indices called keu and
collection of value.
Each key is associated with a single list
The association of keys with values is called key-value pair or item
9. What is difference between list, tuple, dictionary?
A list can store sequence of object in a certain order such that we can
itrate over the list .list is amutable type meaning that list can be
modified after they have been created
A tuple is singler to a list except it is immutable in tuple the element
are enclosed with in parenthis tuple have structure .list have order.
A dictionary is a key-value store .it ts not ordered
10. Define comprenension?
A list comprenension is a convenient way to prodect a list from an
itrable (a sequence or other object then can be itrated over)
11. Give example for list members of ership?
course=['cse','mech','civil','EEE','IT']
Part-B
1. What is list? Explain any list operation with illustrative example.
List:
Ex:
List operation :
There are two operations that can be performed using operators such +
and *
Concatenation using +:
The two lists can be created and can be joined using + operator
following screenshot illustrates it
Ex :
=> L = L1+L2
Repetition using *:
The * is used to repeat the list for number of time following screenshot
illustrate it
Ex :
L=[10,20,30]
[10]*5
List slices:
The : operator used with in the square breaket that it is a list silence
and not the index of the list
Ex
a= [10,20,30,40,50,60]
a[1:4]
[20,30,40,]
a[:]
[10,20,30,40,50,60]
If we omit the first index then the list is considered from the begining
and if we omit the last second index then slice goes to end
If we omit both the first and second index then the list will be displayed
from the beginning to end
List are mutable that means we can change the element of the list hence
it is always better to make a copy of the list before performing any
operations
Ex:
a=[10,20,30,40,50]
a[2:4]=[111,222,333,]
a= [10,20,111,222,333,50]
List Method:
Thus are various methods that can work on the list let us understand
these method with help of illustrative example
i. Append
The append method adds the element at the end of the list
Ex :
a=[10,20,30]
a=[10,20,30,40]
ii. Extend
The extend function take the as an argunment and appends this list at the
end of old list
Ex
a=[10,20,30]
b=['a','b','c']
a,extend(B)
a[10,20,30,'a',b','c']
iii. Sort
The sort method is arrange the elements in increasing order
Ex
a=[5,4,3,1,2]
a.extend(B)
a=[1,2,3,4,5]
Ex
a=['u','v','w','x',y','z']
val=a.pop()
a['u','v','w','x','y']
Ex
a=['a,'b',c',d']
a remove ("C")
[a,b,d]
Ex
a=['a','b','c','d','e']
del a [2:4]
a ['a','b','e']
List loop:
The Loop is used in list for traversing purpore the for loop is to traverse
the list element
Ex
a=['a','b','c','d']
for il in a
print(i)
Syntax :
Opl:
Mutability :
String are immutable that means we cannot modify the string but list are
mutable that means it is possible to change the value of list
If the breacket operation is present on the left hand side than that
element is identified and the list element modified accordingly
Ex
a=['aaa','bbb','ccc']
a[i]=['xxx']
['aaa','bbb','ccc']
Ex
a=['AAA','xxx','ccc']
'xxx' in a true
'BBB' in a false
Aliasing :
An object with more than one reference has more than one name ,So
we say that the object is aliased
Ex
x=[10,20,30]
y=x
y is x true
Ex
x=[10,20,30,]
y=x
y=[10,20,30,]
y[10]=111
y[111,20,30]
x [111,20,30]
Cloning list :
Cloning means creating exact replica of the original list there are various
method using which we can clone the list
i. Cloning by assignment:
We can assign one list to another new list this actually creates a new
reference to the orgined list
EX
a=['a','b','c']
b=a
b['a','b','c']
Note that here list bisa clone of original list a but as the reference is
create a change in one list causes change in another list
Ex
a=[10,20,30]
List a=[10,20,30]
list b =[10,20,30]
Ex
a ['A','B','C']
b=list (a)
b['A','B','C']
a['A','B','C']
List parameters :
Ex
a.append (40)
a=[10,20,30]
a [10,20,30,40]
In above screen short the python code is written in interactive mode the
function insert end is for inserting the element at the end of the list
He we pass the list a as parameter to the function inside the function
the element is added at the end of the list Hence after the making call
element is inserted at the end
2. What is tuple? Explain the tuple assignment with suitable example
Tuple:
Tuple List
Tuple is said to immutable that means onec create we can change the
tuple
Ex
T1=(10,20,30,40)
T2=('a','b','c','d')
T3=('A',10,20)
T4=('aaa','bbb',30,40)
Tuple is written within the peranthisis. even if the tuple contains a single
value , the comma is used as a separator
Ex:
T1=(10)
Ex:
>>>t1=(10,20,'AAA','BBB')
>>>print(t1[0])
>10
>>>print(t1[1:3])
(20,'AAA')
>>>
Tuple Assignment
Ex
>>>a,b=10,20
>>>print (a)
10
>>>print(b)
20
hear the left side is a tuple of variable .the right side is a tuple expression
Each value is assignment its respective varible
All the expression on the right side are evaluated before any of the
assignment
Note that the number of variable on the left and right have to be the
same
we can also separate out the values in the expression in the tuple by
using the split function
Ex
student='AAA,123'
>>>name,roll=student.split(',')
>>>print(name)
AAA
>>>print(roll)
123
A function can only return one value but if the value in tuple .The effect
is the same of returning multiple value
Ex
def student_Info():
name='AAA'
roll=101
return name.roll
Output
>>>t_student _info()
>>>print(t(0))
AAA
>>>print(t(1))
101
>>>+
('AAA',101)
Ex
print (args )
Output
[;AAA',10,89,88)
The above program * accepts the variable number of argument and
inside the function definition there argument sre printed
3. Dictionaries?
In python dictionary is unordered collection of items. These items are in
the form of key value pairs
The dictionary contains the collection of indices called key and
collection of value
Each key associated with single value
The association of key with value is called key value pair or item
Dictionary always represent the mapping of keys with value. Thus each
key maps to value
key value
Ex
>>>my_dictionary=()
>>>my_dictionary =(1;'AAA',2:88)
>>>
Ex
>>>my_dictionary=dict({0:'Red',1:'green',2:'blue'})
We can access the element in the dictionary using the keys following
script illustrates it test,py
Ex
student_dict =('name':'AAA':'roll':10)
print(student_dict['name'])
print(student_dict['rooll'])
Output
AAA
10
Basic operation
Ex
>>>my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})
>>>print(my_dictionary)
{0:'Red',1:'Green',2:'Blue'}
>>>print(my_dictionary)
{0:'Red',1:'Green'2:'Blue',3:'Yellow'}
>>>
Ex
>>>del my_dictionary[2]
{0:'Red',1:'Grreen',3:'Yellow'}
>>>
Ex
>>>my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})
>>>print(my_dictionary)#dispilay of dictionary
{0:'Red',1:'Green',2:'Blue'}
4. Checking length
The len()function gives the number of pairs in the dictionary
Ex
>>>my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})
>>>len(my_dictionary )
>>>
Methods in dictionary
method purpose
poo item remove the item with key and return its v `
value
update([other]) update the dictionary,riturns its value If `
The copy method the copy of the dictionary it does not take any
parameter and return a snallow copy of dictionary
Ex
my dictionary={1:'AAA',2:'BBB',3:'CCC'}
{1:'AAA',2:'BBB',3:'CCC'}
new=dictionary=my_diictionary.copyy()
print(new_dictionary)
{1:'AAA',2:'BBB',3:'CCC'}
Syntax
dictionary fromkey(sequence[,value])
keys = {10,20,30}
values='number'
{10:'number',20:'number',30:'number'}
Syntax
dictionary.get(key [value])
Ex
roll:10
print ("markes":student.get(name))
marks:98
Ex
my -dictionary ={'marks1:99,'marks':96,'marks':97}
dict-value ([99,96,97])
Syntax
pop(key [,defalut])
Where key is the key which is searched for removing the value and
defalut is the value which is to be returned when the key is not the
dictionary
Ex
my-dictionary = {1:'red',2:'blue',3:'green'}
>>>val=my_dictinary.pop(5,3)
>>>
4. Illustretive programs?
1. Selection sort
scan the array to find the smallest element and swap it with the first
element.
Then starting with the second element scan the eutire list to find the
smallest element and swap it with in second element
Ex
70,30,20,50,60,10,40
70 30 20 50 60 10 40
min j
1stpass
0 1 2 3 4 5 6
70 30 20 50 60 10 40
min
70 30 20 50 60 10 40
10 30 20 50 60 70 40
2ndpass
0 1 2 3 4 5 6
10 30 20 50 60 70 40
10 30 20 50 60 70 40
10 20 30 50 60 70 40
3rd pass
0 1 2 3 4 5 6
10 20 30 50 60 70 40
4th pass
0 1 2 3 4 5 6
10 20 30 50 60 70 40
10 20 30 50 60 70 40
i smallest element
10 20 30 40 60 70 50
5th pass
0 1 2 3 4 5 6
10 20 30 40 60 70 50
10 20 30 40 60 70 50
10 20 30 40 50 60 70
6thpass
10 20 30 40 50 70 60
i smallest element
10 20 30 40 50 70 60
program
least=i
for k in range(i+1,len(a));
if a[k]<a [least];
least=k
temp = a[least]
a[least]=a[i]
a[i]=temp
a=[50,30,10,20,40,70,60]
print(a)
print(a)
Output
original list as
[50,30,10,40,70,60]
[10,20,30,40,50,60,70]
>>>
2. insertion sort
In this method the element are inserted at their appropiate place. Hence
is the name insertion sort. Let use understand their method with help of
some examples
30,70,20,50,40,10,60
0 1 2 3 4 5 6
30 70 20 50 40 10 60
0 1 2 3 4 5 6
30 70 20 50 40 10 60
0 1 2 3 4 5 6
20 30 70 50 40 10 60
0 1 2 3 4 5 6
20 30 50 70 40 10 60
0 1 2 3 4 5 6
20 30 40 50 70 10 60
10 20 30 40 50 70 60
0 1 2 3 4 5 6
10 20 30 40 50 60 70
sorted zone
Program
for i in rang(1,len(a));
temp=a[i]
k=j
a[k]=a[k-1];
a=[50,30,10,20,40,70,60]
print(a)
insertions ort(a)
print(a)
Output
original liistt is
[50,30,10,20,40,70,60]
[10,20,30,40,50,60,70]
3. Merge sort
return a
left=mergsort (a[:middle])
right=mergsort (a[:midle])
return-merge(left,right)
a=[30,50,10,40,20]
print("before sorting...")
print(a)
print(After sorting...")
print(merge sort(a))
Output
Before sorting
[30,50,10,40,20]
After sorting
[10,20,30,40,50]
>>>