0% found this document useful (0 votes)
21 views23 pages

Unit 4

The document summarizes compound data types in Python including lists, tuples, and dictionaries. It provides examples and explanations of: - What lists are and how they can be used and manipulated using operators, methods, and loops. Common list methods include append(), extend(), sort(), and pop(). - The differences between lists and tuples, with tuples being immutable sequences. - What dictionaries are and how they store data as key-value pairs unlike ordered lists and tuples. - How to clone lists to create copies without linking to the original list.

Uploaded by

Devi D
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)
21 views23 pages

Unit 4

The document summarizes compound data types in Python including lists, tuples, and dictionaries. It provides examples and explanations of: - What lists are and how they can be used and manipulated using operators, methods, and loops. Common list methods include append(), extend(), sort(), and pop(). - The differences between lists and tuples, with tuples being immutable sequences. - What dictionaries are and how they store data as key-value pairs unlike ordered lists and tuples. - How to clone lists to create copies without linking to the original list.

Uploaded by

Devi D
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/ 23

Unit-IV

Compound Data: List, Tuple, Dictionary


Part-A
1. What are list in python? Give example:
 List is a sequence of value enclosed within a square bracket

Ex: [10,20,30,40]

2. What is the use of * operator in association with list in python?


 The * operator is used to repeat the list number of times

EX:[1,2,3,1,2,3,1,2,3,]

3. What is the purpose of extend method in python?


 The extend method takes new list as argument and append it with old
list. Thus using extend list can be combined.
4. What is aliased?
 An object with more than one direction or reference has more than one
name .so we any that the object is aliased.

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)

T2=('a', 'b', 'c', 'd')

6. Difference between tuple and list.

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

>>> 'CSE' in course True

>>>'AE' in course True

12. List out the types of list methods?


 list.append()
 list.insert()
 list.extend()
 list.remove()
 list.pop()
 list.index()
 list.copy()
13. List out the type of sorting techniques?
 insertion sort
 deletion sort
 shell sort
 public sort
 quick sort
 merge sort
 radix sort

Part-B
1. What is list? Explain any list operation with illustrative example.

List:

 list is a sequence of list


 string is also sequence of value. But in string this sequence is of
characters on the order hand. In case of list the value can be of any type
 *the value in the list are called elements or items .These elements are
seperated by commas and enclosed within square bracket.

Ex:

[10, 200, 30] # list of integers

["aaa","bbb,"ccc"] # list of string

[ 'a',10,20,'b','c',33.3] # list of mixed list

[10, 20, ['a','b','c'] # nested list

 The within another list is called nested list


 The list that contains no elements is called empty list. The empty list is
represented by []

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 :

=> [10, 20, 30], [40,50,60]

=> L1 = [10, 20, 30]

=> L2 = [40, 50, 60]

=> L = L1+L2

=> L = [10, 20, 30, 40, 50, 60]

Repetition using *:

 The * is used to repeat the list for number of time following screenshot
illustrate it

Ex :

L=[10,20,30]

[10]*5

[10, 10, 10, 10, 10]

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 append (40) #adding element 40 at the end

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]

iv. Deleting the element


 The Deletion of any element from the list is carried out using varies
function pop, remove, del
 if we do not provide any argument to the pop function that last element
of the list will be delete

Ex

a=['u','v','w','x',y','z']

val=a.pop()

a['u','v','w','x','y']

 if we know value of the element to be deleted then the remove function


is used

Ex

a=['a,'b',c',d']

a remove ("C")

[a,b,d]

 In python it is possible to remove more than


 one element at a time del function

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 :

for variable in list body

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

 Using the in operator we can check whether particular element belong


the list or not
 If the given element is present in the list
 it returns true otherwise false

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

 The association of variable with object is called referenced


 In above example, reference Y is (related using object a
diagrammatically aliasing is show as fallows
 In any change is made in one reference then other object gets affected

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

ii. Cloning by slicing :


 We can create a clone by slicing during this process [:] opeerator is used
for creating the clone

Ex

a=[10,20,30]

List a=[10,20,30]

print ("list b"=b)

list b =[10,20,30]

iii. Clone by copy constructor :


 We can create a clone for the list using copy constructor this is just
similar to clone by slicing the list function is used to create the clone

Ex

a ['A','B','C']

b=list (a)

b['A','B','C']

a['A','B','C']

List parameters :

 A list can be passed as a parameter to the function this parameter in


passed by reference

Ex

def insert end (a)

a.append (40)

a=[10,20,30]

insert end (a)

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 is a sequence of values it is similar to list but there lies difference


between tuple and list

Defference between tuple and list

Tuple List

Tuple use peranthesis List use square bracket

Tuple cannot be change List can be changed

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

How to write tuple ?

 Tuple is written within the peranthisis. even if the tuple contains a single
value , the comma is used as a separator

Ex:

T1=(10)

 The tuple index start at 0

Ex:
>>>t1=(10,20,'AAA','BBB')

>>>print(t1[0])

>10

>>>print(t1[1:3])

(20,'AAA')

>>>

Tuple Assignment

 we can create a tuple by using assignment operator. Multiple assignment


are possible at a time using 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

Tuple as Return value

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

Variable number of argument

 In python, it is possible to have variable number of argument. In that


case the perameter name begins with * then these variable number of
arguments are gather into a tuple

Ex

def student- Into (*args):

print (args )

Output

studend -into {'AAA',10,89,88]

[;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

How to create Dictionary?

 items of the dictionary are written the {} brackets and separeted by


camma
 The key value pair is represented using ; operator. Thet is key :value
 They key are unique and are of immutable types _such as
string,number,tuple

Ex

>>>#creating empty dictionary

>>>my_dictionary=()

>>>#creating a simple dictionary with key as intejer

>>>my_dictionary =(1;'AAA',2:88)

>>>

 we can also creata a dictionary usinng the ward dict()

Ex

>>>my_dictionary=dict({0:'Red',1:'green',2:'blue'})

How to access the elements in dictionary?

 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

Operation and methods

Basic operation

 various operation that can be performed in dictionary


1. Adding item to dictionary
 we can add the item to the dictionary

Ex

>>>my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})

>>>print(my_dictionary)

{0:'Red',1:'Green',2:'Blue'}

>>>my_dictionary[3]='Yellow'#adding the element to the


dictionary

>>>print(my_dictionary)

{0:'Red',1:'Green'2:'Blue',3:'Yellow'}

>>>

2. Remove item from Dictionary


 For removing an item from the dictionary we use the keyward del

Ex

>>>del my_dictionary[2]

#deleting the item from dictionary


>>>print(my_dictionary)#display of dictionary

{0:'Red',1:'Grreen',3:'Yellow'}

>>>

3. Updating the value of the dictionary


 We can update the value of the dictionary by directly assigning the value
to corresponding key position

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

 Following are some commanly used method in dictionary

method purpose

clear remove all items from dictionary

cop() return the copy of dictionary

get(key,[d]) return the value of key. If key dose not


. exit, returned(default , to none)

items return a new view of the dictionary's i `


items(key,value)

poo item remove the item with key and return its v `
value
update([other]) update the dictionary,riturns its value If `

not ,insert key with a value of dand

1. The clear methothd


 The method remove all items from the dictionary this method does not
take any parametes does not retuns anythin

The copy method

 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'}

print (my dictionary)

{1:'AAA',2:'BBB',3:'CCC'}

new=dictionary=my_diictionary.copyy()

print(new_dictionary)

{1:'AAA',2:'BBB',3:'CCC'}

2. The formkey method


 The formkeys() method create a new dictionary from give the sequnce
of elements with a value provider by the user

Syntax

dictionary fromkey(sequence[,value])

keys = {10,20,30}

values='number'

new dict fromkeys (keys,value)

print (new dict)

{10:'number',20:'number',30:'number'}

3. The get method:


 The get() method returns the values for the spcified key if key is in
dictionary this method takes two parameter ke and values the method
can return either key or value or nothing

Syntax

dictionary.get(key [value])

Ex

studend ={'name':' AAA','roll':10,markes':98}

print ("name":studend.get ('roll'))

roll:10

print ("markes":student.get(name))

marks:98

4. The value method :


 The method returns the value object that display the list of value present
in the dictionary

Ex

my -dictionary ={'marks1:99,'marks':96,'marks':97}

print (my - dictionary value())

dict-value ([99,96,97])

5. The pop method :


 This method the pop() method remote and returns an element from a
dictionary having the give key

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_dictionary.pop(1)#removing the element


>>>print ("The poped element is:,val)

The popped element is:Red

>>>val=my_dictinary.pop(5,3)

>>>print("The popped element using default value is",val)

The popped element using value is: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

consiider the element

70,30,20,50,60,10,40

we can store the element in array

70 30 20 50 60 10 40

a(0) A(1) A(2) A(3) A(4) A(5) A(6)

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

i smallest eleement found d

now swap A[i] with smallest element

10 30 20 50 60 70 40
2ndpass

0 1 2 3 4 5 6

10 30 20 50 60 70 40

i scan the element

10 30 20 50 60 70 40

i smallest element swapA[i]with smallest element

10 20 30 50 60 70 40

3rd pass

0 1 2 3 4 5 6

10 20 30 50 60 70 40

i,min smallest element is searched

 As there is no smallest element then 30 we will increment i pointer

4th pass

0 1 2 3 4 5 6

10 20 30 50 60 70 40

i,min smallest element is searched

10 20 30 50 60 70 40

i smallest element

swap A[i] with 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

i search smallest element

10 20 30 40 60 70 50

min search smallest element


swap A[i] with smalest element

10 20 30 40 50 60 70

6thpass

10 20 30 40 50 70 60

i smallest element

swap A[i] with smallest element

10 20 30 40 50 70 60

This is a sorted array:

program

def slectionsort(a): #function definition

for i in range (len(a)):

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("original list is ...")

print(a)

slectionshort(a) #call to the function

print("The sort list is ...")

print(a)

Output
original list as

[50,30,10,40,70,60]

the sorted list is

[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

consider a list of element

30,70,20,50,40,10,60

The process stats with first element

0 1 2 3 4 5 6

30 70 20 50 40 10 60

sorted zone unsorted zone

0 1 2 3 4 5 6

30 70 20 50 40 10 60

sorted zone unsorted zone

0 1 2 3 4 5 6

20 30 70 50 40 10 60

sorted zone unsorted zone

0 1 2 3 4 5 6

20 30 50 70 40 10 60

sorted zone unsorted zone

0 1 2 3 4 5 6

20 30 40 50 70 10 60

sorted zone unsorted zone


0 1 2 3 4 5 6

10 20 30 40 50 70 60

sorted zone unsorted zone

0 1 2 3 4 5 6

10 20 30 40 50 60 70

sorted zone

Program

def insertion sort (a);

for i in rang(1,len(a));

temp=a[i]

k=j

while>0 and temp <a(k-1)

a[k]=a[k-1];

a=[50,30,10,20,40,70,60]

print ("original list is ....")

print(a)

insertions ort(a)

print("The sorted list is ...")

print(a)

Output

original liistt is

[50,30,10,20,40,70,60]

The sorted list is

[10,20,30,40,50,60,70]

3. Merge sort

def merge sort (a)


if len (a)<2;

return a

middle=int (len (a)/2)

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]

>>>

You might also like