0% found this document useful (0 votes)
16 views85 pages

Tuples Lists Dictionaries

A tuple is an immutable ordered set of values identified by indices, which can contain elements of any type, including other tuples. Tuples are created using parentheses and can be accessed via positive or negative indexing, with operations such as concatenation and repetition available. Built-in methods for tuples include counting occurrences, finding indices, and determining maximum and minimum values.

Uploaded by

muhammedfuaadc
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)
16 views85 pages

Tuples Lists Dictionaries

A tuple is an immutable ordered set of values identified by indices, which can contain elements of any type, including other tuples. Tuples are created using parentheses and can be accessed via positive or negative indexing, with operations such as concatenation and repetition available. Built-in methods for tuples include counting occurrences, finding indices, and determining maximum and minimum values.

Uploaded by

muhammedfuaadc
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/ 85

TUPLES

➢ A Tuple is an ordered set of values, where each value is identified by an index.


➢ The values that make up a tuple are called its elements.

➢ Individual elements can be of any type, even another tuple.

➢ Tuple is Immutable .Because we can’t modify the elements in a Tuple

CREATING A TUPLE

➢ A Tuple created by enclosing the all the elements inside parenthesis () separated by commas
tuple name=(element1,element2,…….)

Example: a= (10, 20, 30, 40)


s= (“Python", “Java", “C“)
t= ( "hello“ , 2.0, 5, [10, 20] , (“Python”, “Java”) )

• The last tuple contains a string, a float, an integer, list and another tuple
• If a tuple contains another tuple it is known as nested tuple. Here t is a nested tuple.
➢ A Tuple that contains no elements is called the empty tuple.
Eg: b = ()

DISPLAYING A TUPLE
Eg: numbers=(1,2,3,4,5)
print numbers Output: (1,2,3,4,5)
DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
ACCESSING TUPLE ELEMENTS

➢ The elemets are accessed by using index numbers. The index start at 0.
➢ The index of first element is 0,second element is 1,third element is 2 and so on.
➢ If tuple contains ‘n’ elements index number varies from 0 to (n-1)
➢ Python allows negative indexes for tuple elements. The negative index starts from -1(last element)
➢ The negative index of last element is -1,second last element is -2, and so on.

Eg1: a=(2,4,8,12)

-ve index -4 -3 -2 -1
+ve Index 0 1 2 3
Element 2 4 8 12

Print a[2] Output: 8

print a[-3] Output :4

DHANYA V,AP IN IT,CEV

2
Downloaded from Ktunotes.in
Eg2:T1=( “Happy” , 20 , [2,10,1,5] , (44,55) )
print T1 [2] Output: (2,10,1,5)
Print Tl[1] Output :20
Print T1[2] [1] Output:10
Print T1[3] Output (44,55)
Print T1[0][1] Output :a

TUPLE LENGTH
➢ The function len is used to find the length of a TUPLE(number of elements in the TUPLE)

Syntax: len(tuple name)


Eg1: t1=(20,30,40,50,60)
l=len(t1) l=5
Eg2: t1=( “Happy” , 20 , [2,10,1,5] )
l=len(t1) l=3

TUPLE TRAVERSAL

➢ A lot of computations involve processing a list one element at a time.


➢ We may start at the beginning, select each element in turn, and continue until the end. This pattern of processing
is called a traversal.
➢ Traversal can be done with while or for loops.

DHANYA V,AP IN IT,CEV

3
Downloaded from Ktunotes.in
Eg: a=(11,22,33,44)
Using while loop Using for loop

i=0 i)for i in range (0,len(a)):

while i<len(a) print a[i]

print a[i]
i=i+1 Easy method
ii)for i in a:
print i

Output: 11
22
33
44

DHANYA V,AP IN IT,CEV

4
Downloaded from Ktunotes.in
TUPLE SLICING
➢A slice is a subset of a tuple .
➢Slice operator (:) is used to extract a slice of the tuple
Syntax: tuple name[n : m : stepsize]
returns the subset of the list from the nth element(including) to the mth element(excluding)
Eg: s=(1,2,3,4,5,6,7,8)

1.s[0:5:1] Output: (1,2,3,4,5)


2.s[3:7:1] Output: (4,5,6,7)
3.s[2:6:2] Output: (3, 5)
4.s[1:4] Output: (2,3,4)
5.s[-2:-7:-1] Output: (7,6,5,4,3)
6.s[-5:-2] Output : (4,5,6)

DHANYA V,AP IN IT,CEV

5
Downloaded from Ktunotes.in
➢If you omit the first index (before the colon), the slice starts from beginning of the tuple. If you
omit the second index, the slice goes to the end of the tuple.(+ve step size)
➢If you omit the first index (before the colon), the slice starts from end of the tuple. If you omit
the second index, the slice goes to the beginning of the tuple.(-ve step size)

s=( “Hello” , 11 , 5 , 3 , 4.5 , ’x’ ,10 )

1.s[:5:1] : (“hello”, 11, 5, 3, 4.5)


2.s[:4:] : (“hello”, 11, 5, 3)
3.s[2::2] : (5,4.5,10)
4.s[2::] : (5 , 3 , 4.5 , ’x’ ,10 )
5.s[2::-1] : (5,11,,”Hello”)
5.s[::] : (“Hello” , 11 , 5 , 3 , 4.5 , ’x’ ,10 )
6.s[::-1] : (10, ’x’ , 4.5 , 3 , 5 , 11 , ”Hello”)

DHANYA V,AP IN IT,CEV

6
Downloaded from Ktunotes.in
CHANGING A TUPLE
➢ Unlike lists, tuples are immutable.
➢ This means that elements of a tuple cannot be changed . But, if the element is itself a mutable
data type like list, its nested items can be changed.
Eg: x=(1,2,5, [3,8,9] )
x[3][1] =88 Now,x : (1,2,5, [3,88,9] )
DELETING TUPLE ELEMENTS
➢ we can delete an entire tuple
Syntax : del tuple name
Eg: x=(2,5,3,8,9)
del x will delete the entire tuple.

➢ we cannot change or delete the elements in a tuple. But if the element is itself a mutable data
type like list, its nested items can be deleted.
Eg: x=(1,2,5, [3,8,9] )
del x[3][1] Now,x : (1,2,5, [3,9] )

DHANYA V,AP IN IT,CEV

7
Downloaded from Ktunotes.in
TUPLE OPERATIONS
➢ There are 4 basic tuple operations in Python
1. concatenation 2.Repetition 3. in 4. not in

1. concatenation (+)
❑ Joins two tuples
Eg: x=(1,2,3,4)
y=(10,20,30)

z=x + y z: (1,2,3,4,10,20,30)

2.Repetition (*)
❑ This operator replicates the elements in the tuple
Eg: a=(1,2,3)
b=3*a b : (1,2,3,1,2,3,1,2,3)

DHANYA V,AP IN IT,CEV

8
Downloaded from Ktunotes.in
3. in
❑ Used to check whether an element present in a tuple.
❑ Returns true if element is present .Otherwise returns false.
Eg1: X=(2,5,3,8,9)
if(2 in X):
print ”Present”
else:
print”Not Present”

4. not in
❑ Used to check whether an element not present in a tuple
❑ Returns true if element is not present .Otherwise returns false.
Eg: X=(2,5,3,8,9)
if(2 not in X):
print ”Not Present”
else:
print”Present”
DHANYA V,AP IN IT,CEV

9
Downloaded from Ktunotes.in
BUILT IN TUPLE METHODS (FUNCTIONS)
count()
❑ This method is used to count the no.of occurences of an element in a tuple
Syntax: tuplename. count(element)
Eg: a=(1,2,3,4,3,5,1,9,1)
b= a.count(1)
b=3

index()
❑ This method is used to find the lowest index of an element in a tuple
Syntax: tuplename. index(element)
Eg: a=(1,2,3,4,3,5,1,9,1)
b= a.index(3)
b=2

max()
❑ This method is used to find the largest element in a tuple.
Syntax: max(tuple name)
Eg: a= (33,28,99,10)
b=max(a) b:99
min()
❑ This method is used to find the smallest element in a tuple.
Syntax: min(tuple name)
Eg: a= (33,28,99,10)
b=min(a) b:10
DHANYA V,AP IN IT,CEV 10
Downloaded from Ktunotes.in
Sorted()
❑ This method is used to store the sorted elements of a tuple in another tuple
Syntax: tuple1=sorted(tuple2) : By default the elements are stored in asc. order
Eg: a=(“C”, ”Python” ,”Java”)
b=sorted(a)
Then b = (“C”, ”Java” , ”Python”)
❑ For sorting in descending order
Syntax: tuple1=sorted(tuple2,reverse=True)
Eg: a=(“C”, ”Python” ,”Java”)
b=sorted(a, reverse = True)
Then b = (“Python”, ”Java” , ”C”)

DHANYA V,AP IN IT,CEV

11
Downloaded from Ktunotes.in
Advantages of Tuple over List
Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain
advantages of implementing a tuple over a list. Below listed are some of the main advantages:
• Since tuples are immutable, operations with a tuple is faster than with list.
• Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
Python Program to Swap Two Numbers using Tuple
a= input("Enter the first number :") Largest and smallest element in a set of
b=input("Enter the second number :") numbers using list
print “Before swap: a=", a, "b=",b x = []
(a,b)=(b,a)
n=input(“How many numbers?”)
print“ Afetr Swap: a=",a, "b=",b
print "\nEnter the numbers"

TUPLE PACKING & UNPACKING for i in range(1,n+1):


Tuple packing refers to assigning multiple values into a tuple. k=raw_input()
Eg:cstudent = (“Surya” , 10, 249) This tuple stores the name,roll no and mark x.append(k)
of a student print “List is:” ,x
Tuple unpacking refers to extracting tuple values back into multiple variables. l=max(x)
Eg: (n,r,m) = student s=min(x)
The tuple values are assigned to the variables n,r,m in that order Print “Largest =“ , l , “Smallest=“,s
ie n= Surya”
r=10
m=249

DHANYA V,AP IN IT,CEV 12


Downloaded from Ktunotes.in
STRINGS IN PYTHON
➢ A string datatype is used to store a group of characters.Group of chatacters can be encosed
within Singe quotes or double quotes.
Eg: s1= “Hello World”
s2= ‘Python’
s3=‘ ’
s4=“ ”
name=“Johnson”
s1,s2,s3,s4,name are string variables

.
READING A STRING FROM KEYBOARD
➢ raw_input() is used in Python2
Eg: s= raw_input(“Enter a string”)
The string entered from keyboard is stored in the variable ‘s’
➢In Python3, input() is used
Eg: s= input(“enter a string”)

DHANYA V,AP IN IT,CEV 1


Downloaded from Ktunotes.in
ACCESSING INDIVIDUAL CHARACTERS IN THE STRING
➢ The index values of characters starts from 0. .
Eg: s1= “Hello World”

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 - VE INDEX NOS


0 1 2 3 4 5 6 7 8 9 10 + VE INDEX NOS
H e l l o W o r l d

s1[0] =‘H’ s1[1]=‘e’ etc

➢we can use negative indices, which count backward from the end of the string.
.

s1[-1] =‘d’ , s1[-2] =‘l’ and so on.


STRING LENGTH
➢ The len is a built-in function that returns the number of characters in a string(string length) .
Eg: s= “Program”
n=len(s)
The value of n will be 7
DHANYA V,AP IN IT,CEV 2
Downloaded from Ktunotes.in
TRAVERSAL IN THE STRING
➢ A lot of computations involve processing a string one character at a time.
➢ We may start at the beginning, select each character in turn, do something to it, and continue
until the end. This pattern of processing is called a traversal.
➢ String Traversal can be done with while or for loops.

Eg: Using while loop Using for loop


s=“Hello” for i in range (0,len(s)): len (s) = no.of characters in s= 5

i=0 print s[i] i varies from 0 to 4


S[i] means each character in the string
while i<len(s)
S[0]= H s[1]= e etc
. print s[i]
i=i+1
Another Method Using for loop(Easy method)
i)for i in s:
Here i represents each character in the string s
print i
DHANYA V,AP IN IT,CEV

3
Downloaded from Ktunotes.in
STRING OPERATORS

1.STRING CONCATENATION
➢+ operator is used
Eg:
s1=“Hello”
s2=“World”
s3=s1+s2
print s3
2.STRING COMPARISON
➢ ==, != , <, <= , > , >= operators are used
. Eg:
s1=raw_input()
s2=raw_input()
if (s1==s2):
print “Equal”
elif(s1<s2):
print “s1 precedes s2”
else:
print”s1 succeeds s2”
DHANYA V,AP IN IT,CEV 4
Downloaded from Ktunotes.in
3.STRING REPLICATION USING * OPERATOR
➢Used to repeat a string for a given no.of times
s=“Hello ”
s2=s*3
print s2

Output : HelloHelloHello
4.IN AND NOT IN OPERATORS
➢Used to check whether a character occurs in a string

s=“Hello ” s=“Hello ”
if(‘e’ in s): if(‘e’ not in s):
print (“Present”) print (“Not Present”)
else: else:
print “Not Present” print “Present”
Output : Present Output : Present

DHANYA V,AP IN IT,CEV 5


Downloaded from Ktunotes.in
➢ Python does not handle upper- and lowercase letters. All the uppercase letters come before all
the lowercase letters.

➢Strings are Immutable. Ie we can't change the characters in a string. But we can
delete the entire string
Eg:
greeting = "Hello, world!"
greeting[0] = 'J' # ERROR!
print greeting

Deleting an entire string


Syntax:
. del string name
s=“Hello”
del s

DHANYA V,AP IN IT,CEV

6
Downloaded from Ktunotes.in
STRING SLICES
➢A segment(part) of a string is called a slice
➢Slice operator (:) is used to extract a part (slice) of a string
Syntax: string name[n : m : stepsize]
returns the part of the string from the nth character to the mth character, including the first
character but excluding the last

Eg: s= “Program”

1.s[0:5:1] - Progr
.

2.s[3:7:1] -gram If step size is not given default value = 1

3.s[2:6:2] - or
4.s[1:4] - rog
DHANYA V,AP IN IT,CEV
5.s[-2:-7:-1] -margo
6.s[-5:-2] -gra 7
Downloaded from Ktunotes.in
➢If you omit the first index (before the colon), the slice starts at the beginning of
the string. If you omit the second index, the slice goes to the end of the string.
1.s[:5:1] - Progr
2.s[:4:] OR s[:4] - Prog
3.s[2::2] - orm
4.s[2::] OR s[2:] - ograms
5.s[::] OR s[:] OR s[::1] - Programs
6.s[::-1] - smargorP
.

DHANYA V,AP IN IT,CEV

8
Downloaded from Ktunotes.in
STRING FUNCTIONS(METHODS)

1.find() method
➢Used to find the index of a given character in the string. If character is not present the
function returns -1 0 1 2 3 4 5
Syntax: string.find(character) P y t h o n
Eg:
s=“Python”
n1=s.find(‘t’) - Output : 2
n2=s.find(‘k’) - Output : -1
➢Also used to search whether a substring is present in a given string. If substring is present it
returns the starting index of substring.If not present the function returns -1
s=“Python”
n1=s.find(‘tho’) - Output : 2 ( starting index of substring)
n2=s.find(‘the’) - Output : -1 (substring not present)

DHANYA V,AP IN IT,CEV 9


Downloaded from Ktunotes.in
2.count() method
➢Used to find the no.of occurrences of a substring or character present in a given string. If
substring or character is not present the function returns -1
s=“substring search in a string”
Syntax: string.find(substring/character)
n1=s.count(‘in’) - Output : 3
n2=s.count(‘ing’) - Output : 2
n3=s.count(“search”) - Output :1
n4=s.count(“t”) – Output : 2

3.replace() method
➢Used to return a copy of a string in which a given substring or character is replaced with
another.
Syntax: string.replace(substring,newsubstring)
string.replace(character, new character)
Eg1 s=“Hello good morning”
s2=s.replace(“morning”,”evening”) - s2: Hello good evening

Eg2 s=“Hello good morning”


s2=s.replace(“ ”, ”*”) - s2: Hello*good *morning (Here space is replaced with *) 10
Downloaded from Ktunotes.in
4.Split() method
➢Used to split a string based on a delimiter and returs a list of words
Syntax: s.split(delimiter)
s= “hello World”
s2=s.split(“ “) → String splits at space - s2: [ ‘hello’ , ‘World’] (s2 - list of words)
s= “hello, How Are U”
s2=s.split(“ , “) → String splits at , - s2: [ ‘hello’ , ‘How Are U’]

5.join() method
➢Used to join a list of words by using a delimiter (Eg: hyphen -) and returns a string
Syntax: delimiter.join(list of words)
s2=[ ‘hello’ , ‘World’]

s3= - . join(s2)
Then s3: hello-World (The words are joined by using – and stored in s3)

DHANYA V,AP IN IT,CEV 11


Downloaded from Ktunotes.in
6.upper() method
➢Used to produce an uppercase copy of the string .
Syntax: string.upper()
s=“Hello”
s2=s.upper() - s2 : HELLO

7.lower() method
➢Used to produce a lowercase copy of the string .
Syntax: string.lower()
s=“HELLO”
s2=s.lower() - s2: hello

8.capitalize() method
➢ Used to produce a copy of the original string and converts the first character of the string to a
capital (uppercase) letter and converts all other characters in to lowercase letters
Eg: s=“hello how are U”
s2=s.capitalize() - s2: Hello how are u

DHANYA V,AP IN IT,CEV 12


Downloaded from Ktunotes.in
9.min() method
➢Used to return the minimum alphabetical character from a string .
Syntax: min(string)
s=“Hello”
s2=min(s) - s2: H (In Python All the uppercase letters come before all the lowercase letters

10.max() method
➢Used to return the maximum alphabetical character from a string .
Syntax: max(string)
s=“Hello”
s2=max(s) - s2: o

DHANYA V,AP IN IT,CEV 13


Downloaded from Ktunotes.in
STRINGS-UNIVERSITY QUESTIONS
2019 SCHEME UNIV QNS

Ans)
x = raw_input(“Enter a sentence:”)
a= x.split(“ “)
print a

str1 = raw_input(“Enter a string:”)


Stores the last 3 characters of the string in ‘y’
y=str1[-3: :]
if(y != “ing” ):
str2=str1 + “ing”
else:
str2=str1 + “ly”

(b) Write a Python program to reverse a string and print whether its palindrome or
not. (8)
Ans)
s= raw_input(“Enter a string”)
s[::-1] means last character to first character ie reverse
s2=s[::-1]
print “Reverse:”,s2
if(s==s2):
print “Palindrome”
else:
print “Not Pal”

Downloaded from Ktunotes.in


Ans)
s= raw_input(“Enter a string”)
s2=s.upper()
print “Uppercase string:” ,s2
x= raw_input(“Enter a substring”)
k=s.count(x)

if(k==-1):
print”Substring not found”
else:
print “No.of occurrences:”, k

Ans)
s1= raw_input(“Enter first string”)
s1= raw_input(“Enter second string”)
if(s1==s2):
print “Equal”
else:
print “Not”

Q.Let s=’Hello World’ be a string. What will be the output of following


expressions?
i) s[0:7] ii) s[-3] iii) s[::-1] iv) len(s) v) s[8:0:-2] vi) s[2::]

Ans) i) Hello Wo ii) r iii) dlroW olleH iv) 11 v) rWol vi) llo World

Downloaded from Ktunotes.in


Q
Consonents -> Non vowels
alphabets other than a,e,i,o,u
Ans) s= raw_input(“Enter a string”) Store s in s1 after converting in to same
c1=c2=c3=c4=0 case (here lowercase)
s1=s.lower() Otherwise while checking for vowels &
for k in s1: consonents we need to check uppercase
and lowercase letters separately
if(k==’a’ or k==’e’ or k==’i’ or k==’o’ or k==’u’):
c1=c1+1 This condition is checked only if the
condition in the if part is false
elif( (k>=’a’ and k<=’z’ ) ): .ie character is not a vowel.So here we
c2=c2+1 Check whether character is a non
vowel alphabet(consonant)
elif(k==’ ’ or k==’\t’):
c3=c3+1 This condition is checked only if the
condition in the if part and first elif
elif(k==’?’):
part are false.
c4=c4+1 .ie character is not a vowel or
consonant.So here we Check whether
print “No.of Vowels :” c1
the character is a single space or tab
print “No.of consonents:” , c2 space. If so word count is incremented
print “No.of words:” ,c3 . Because here we assume that words
print “No.of qn marks:”,c4 are separated by single space or tab
space
This condition is checked only if first
3 conditions are false.
.

Ans). Yes .string is immutable. we cant change individual characters of string. So


there is error in the code. we can’t store the character ‘P’ at index 0 by replacing ‘J’

Downloaded from Ktunotes.in


2015 SCHEME REPEATED UNIV QNS

Ans)
Since string is immutable we
s= raw_input(“Enter a string”) cant change original string s.
for k in s: Here we store s in s2 by
if(k=='a' or k=='e' or k=='o'): replacing vowels with null
s2=s.replace(k,"") string
print s2

Ans) Type Error. Because strings are Immutable and we cant modify the individual
characters
Since string is immutable we
one = “This a test”
cant change original string s.
s2=s.replace(‘i’,’u’) Here we store s in s2 by
print s2 replacing ‘i’ with ‘u’

Ans) Here s is stored in s2 by replacing


s= raw_input(“Enter a string”) the substring x with y
x= raw_input(“Enter a substring”)
y= raw_input(“Enter another substring”)
s2=s.replace(x,y)
print s2

Downloaded from Ktunotes.in


Q

Ans)
s= “mary had a little lamb”
s2=s.replace(“lamb”,”kid”)
k=s.find(“had”)
print k

Ans) i) 6 ii) appl iii)Error-String index out of range iv) p

Let s=”Hai”
s= raw_input(“Enter a string”) last index: 2 (ie len(s)-1)
for i in range(len(s)-1 , -1, -1): first index =0
print s[i], i varies from len(s) to 0 for traverse
in reverse order .
So…for i in range(len(s)-1,-1,-1)
If we need to get index 0 then final
value should be -1.
Step size should be decreased by 1.

Refer Note

Downloaded from Ktunotes.in


Q

9 Ans) i) String operations in pyth ii) String operations in python

iii) rations in python iv) pyth

10 Ans) s= raw_input(“Enter a string”)


s2=s*20
print s2

11 Ans) Refer 2nd qn

i) a) oran b) Error-String index out of range c) a d)naro

ii) s= ‘How are you’


Here, x= [‘How’ , ‘are’ , ‘you’]
x=s.split(“ “) Next, These words are joined by using
s2=’-‘ . join(x) – and stored in s2
print s2

Downloaded from Ktunotes.in


2015 SCHEME OTHER QNS

Ans) s= raw_input(“Enter a string”)


print “Menu \n 1.Slice \n 2.Replace”
n=input(“Enter choice”)
if(n==1):
s1=s[0::2] Here, s[0::2] means characters at even
s2=s[1::2] indices and s[1::2] contains characters
print s1 at odd indices

print s2
elif(n==2):
c=0
• Here, first we check whether the string
for k in s: contains spaces(space count is stored in c)
if(k==" "): • if no.of spaces in string s =0 it is stored in
c=c+1 another string s2 by adding a ‘$’
if(c==0): character at the start and end by using +
s2='$'+s+'$' operator
• If string s contains spaces it is stored in
else:
another string s2 by replacing spaces with
s2=s.replace(" ","*") *
print s2

Downloaded from Ktunotes.in


Q

10Ans) n= string length(no.of caharacters)


s= raw_input(“Enter a string(even length)”) for an even lengthed string s the index of
n=len(s) first half will be from 0 to n/2 -1
s1=s[0:n/2] index of 2nd half will be from n/2 to n-1
s2=s[n/2:] For eg. if length n= 6
frst half: 0 to 2
s3=s1[::-1]+s2[::-1]
sec half : 3 to 5
print s3
s1 stores first half and s2 stores 2nd half
reverse of s1 and s2 are combined and
11 Ans) stored in s3

s= raw_input(“Enter a string”) The result of s[0::2] is the characters at


s1= s[0::2] even indices.
print s1

Ans i) s= raw_input(“Enter a string”) iii) s= raw_input(“Enter a string”)


s2=s[::-1] x= raw_input(“Enter a character”)
print “Reverse”, s2 for i in range(0,len(s)-1,1):
if(s[i]==x):
ii) s= raw_input(“Enter a string”) print “Found at index :”, i
x= raw_input(“Enter a sub string”) c= s.count(x)
k=s.find(x) print “No.of occurrences:”,c
if(k==-1):
print”Substring Not Present”
else:
print “Present”

Downloaded from Ktunotes.in


Q

s= raw_input(“Enter a string”)
n=len(s)
f=0
for i in range(0,n/2,1):
if(s[i]!= s[n-i-1]):
f=1
break
if(f==0):
print "Palindrome"
else:
print "Not"

Downloaded from Ktunotes.in


LISTS
➢ A list is an ordered set of values, where each value is identified by an index.
➢ The values that make up a list are called its elements.

➢ Individual elements can be of any type, even another list.

➢ List is MUTABLE .Because we can insert ,delete or modify the elements in a list

CREATING A LIST(Direct method)


➢ A list created by enclosing the all the elements inside square brackets ([ ]) separated by
commas
list name=[element1,element2,…….]

Example: a= [10, 20, 30, 40]


s=[“Python", “Java", “C"]
list1= ["hello", 2.0, 5, [10, 20]]

• The last list contains a string, a float, an integer, and another list
• If a list contains another list it is known as nested list. Here list1 is a nested list.
DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
➢ There is a special list that contains no elements. It is called the empty list.

Eg: b = []
CREATING A LIST BY READING ELEMENTS FROM KEYBOARD

x = []
n=input(“enter the no.of elements”)
print "\n Enter the Elements"
for i in range(1,n+1): Inside the for loop ‘n’ numbers are
entered and appended to the list
k=input()
x. append(k)

DISPLAYING A LIST
Syntax: print listname
Eg: x =[1,2,3,4,5]
print x Output: [1,2,3,4,5]

DHANYA V,AP IN IT,CEV 2


Downloaded from Ktunotes.in
ACCESSING LIST ELEMENTS
➢ The elemets are accessed by using index numbers. The index start at 0.
➢ The index of first element is 0,second element is 1,third element is 2 and so on.
➢ If list contains ‘n’ elements index number varies from 0 to (n-1)
➢ Python allows negative indexes for list elements. The negative index starts from -1(last
element)
➢ The negative index of last element is -1,second last element is -2, and so on.

Eg1: a=[2,4,8,12]

-ve index -4 -3 -2 -1
+ve Index 0 1 2 3
Element 2 4 8 12

Print a[2] Output: 8

Print a[-3] Output :4

DHANYA V,AP IN IT,CEV 3


Downloaded from Ktunotes.in
Eg2: list1=[“Physics”,2016,90.5]

Print list1[2] Output: 90.5

Print list1[0] Output :Physics

Eg3: list1=[ “Happy” , 20 , [2,10,1,5] ]

Print list1[2] Output: [2,10,1,5]

Print list1[1] Output :20

Print list1[2] [1] Output:10

Print list1[1] Output :20

Print list1[0][1] Output :a

DHANYA V,AP IN IT,CEV 4


Downloaded from Ktunotes.in
LIST LENGTH
➢ The function len is used to find the length of a list(number of elements in the list)

Syntax: len(list name)

Eg1: num=[ 2,4,6,8 ]

l=len(num) l=4

Eg2: list1=[ “Happy” , 20 , [2,10,1,5] ]

l=len(list1) l=3

LIST TRAVERSAL
➢ A lot of computations involve processing a list one element at a time.
➢ We may start at the beginning, select each element in turn, do something to it, and
continue until the end. This pattern of processing is called a traversal.
➢ List Traversal can be done with while or for loops.

DHANYA V,AP IN IT,CEV 5


Downloaded from Ktunotes.in
Eg: a=[1,2,3,4]
Using while loop
Using for loop
i=0 len (a) = no.of elements in a= 4
for i in range (0,len(a)):
while i<len(a) i varies from 0 to 3
print a[i]
print a[i] a[i] means each element in the list a
i=i+1 a[0]= 1 a[1]= 2 etc

Another Method Using for loop(Easy method)


Output: 1
for i in a: 2
Here i represents each element in the list a
print i 3
Ie i=1 print1
4
i=2 print 2 etc

DHANYA V,AP IN IT,CEV 6


Downloaded from Ktunotes.in
Eg: s=[“Physics” ,”Chemistry”,”Maths”]

for i in s:
print i

Output: Physics
Chemistry
Maths

DHANYA V,AP IN IT,CEV 7


Downloaded from Ktunotes.in
LIST SLICING
➢A slice is a subset of a list .
➢Slice operator (:) is used to extract a slice of the list
Syntax: list name[n : m : stepsize]
returns the subset of the list from the nth element(including) to the mth element(excluding)
Eg: s=[1,2,3,4,5,6,7,8]

1.s[0:5:1] Output: [1,2,3,4,5]


2.s[3:7:1] Output:[4,5,6,7]
3.s[2:6:2] Output:[3, 5]
4.s[1:4] Output:[2,3,4]
5.s[-2:-7:-1] Output:[7,6,5,4,3]
6.s[-5:-2] Output :[4,5,6]

DHANYA V,AP IN IT,CEV 8


Downloaded from Ktunotes.in
➢If you omit the first index (before the colon), the slice starts from beginning of the list. If you
omit the second index, the slice goes to the end of the list.(+ve step size)
➢If you omit the first index (before the colon), the slice starts from end of the list. If you omit the
second index, the slice goes to the beginning of the list.(-ve step size)

s=[ “Hello” , 11 , 5 , 3 , 4.5 , ’x’ ,10 ]

1.s[:5:1] : [“hello”,11,5,3,4.5]
2.s[:4:] OR s[:4] : [“hello”,11,5,3]
3.s[2::2] : [5,4.5,10]
4.s[2::] OR s[2:] : [5 , 3 , 4.5 , ’x’ ,10 ]
5.s[2::-1] : [5,11,,”Hello”]
5.s[::] OR s[::1] : [“Hello” , 11 , 5 , 3 , 4.5 , ’x’ ,10 ]
6.s[::-1] : [10, ’ x’, 4.5, 3, 5, 11, ”Hello”]

DHANYA V,AP IN IT,CEV 9


Downloaded from Ktunotes.in
DELETING LIST ELEMENTS & ENTIRE LIST

➢ del statement can be used if we know exactly which element is deleting.


Eg: list1=[2,5,3,8,9]
del list1[1] will delete the element at index 1
list1 becomes:[2,3,8,9]

DELETING AN ENTIRE LIST


list1=[2,5,3,8,9]
del list1 will delete the entire list.

DELETING A PART OF THE LIST


list1=[2,5,3,8,9]
del list1[1:3] will delete the elements at index1 and index2
list1 becomes: [2,8,9]

DHANYA V,AP IN IT,CEV 10


Downloaded from Ktunotes.in
LIST OPERATIONS
➢ There are 4 basic list operations in Python
1. concatenation 2.Repetition 3. in 4. not in

1. concatenation (+)
❑ Joins two lists
Eg: list1=[2,5,3,8,9]
The elements in list1 and
list2=[3,10,20] list2 are combined and
stored in list3
list3=list1+list2 list3= [2,5,3,8,9,3,10,20]

2.Repetition (*)
❑ This operator replicates the elements in the list
The elements in list1 are
Eg: list1=[2,5,8] replicated 3 times and
list2=3*list1 list2=[2,5,8,2,5,8,2,5,8] stored in list2

DHANYA V,AP IN IT,CEV 11


Downloaded from Ktunotes.in
3. in
❑ Used to check whether an element present in a list.
❑ Returns true if element is present .Otherwise returns false.
Eg: list1=[2,5,3,8,9]
if(2 in list1):
print ”Present”
else:
print”Not Present”

4. not in
❑ Used to check whether an element not present in a list.
❑ Returns true if element is not present .Otherwise returns false.
Eg: list1=[2,5,3,8,9]
if(2 not in list1):
print ”Not Present”
else:
print”Present”
DHANYA V,AP IN IT,CEV 12
Downloaded from Ktunotes.in
BUILT IN LIST METHODS (FUNCTIONS)
append()
❑ This method is used to add an element to the end of a list
Syntax: listname.append(element)
Eg: a=[1,2,3,4]
a.append(90)
Now a becomes [1,2,3,4,90]

extend()
❑ This method is used to add all the elements of a sequence at the end of a list
Syntax: listname.extend(sequence)
Eg: a=[1,2,3,4] b=[5,6,7]
a.extend(b)
Now a becomes [1,2,3,4,5,6,7]

DHANYA V,AP IN IT,CEV 13


Downloaded from Ktunotes.in
insert()
❑ This method is used to insert an at a specified index in a list
Syntax: listname.insert(index,element)
Eg: a=[“C”, ”Python” ,”Java”]
a.insert(1,”C++”)
Now a becomes = [“C”, “C++” , ”Python” ,”Java”]
NOTE: Suppose we want to replace an element with another element,
Eg: list1=[2,5,3,8,9]
We want to replace element at index position 2 (ie 3) with 300.
list1[2]=300. Now list1=[2,5,300,8,9]

remove()
❑ This method is used to remove a given element from a list
Syntax: listname. remove(element)
Eg: a=[“C”, ”Python” ,”Java”]
a.remove(“Python”)
Now a becomes : [“C” ,”Java”]
DHANYA V,AP IN IT,CEV 14
Downloaded from Ktunotes.in
pop()
❑ This method is used to remove an element from a given index from a list
❑ If no index is given, it removes the last element.
Syntax: listname. pop(index)
Eg: a=[“C”, ”Python” ,”Java”]
b=a.pop(0) b:”C”
c=a.pop() c:”Java”

NOTE: Another way to delete an element at an index


➢ del statement can be used to delete an element at an index
Eg: list1=[2,5,3,8,9]
del list1[1] will delete the element at index 1
list1 becomes:[2,3,8,9]

DHANYA V,AP IN IT,CEV 15


Downloaded from Ktunotes.in
index()
❑ This method is used to find the lowest index of an element in a list
Syntax: listname. index(element)
Eg: a=[1,2,3,4,3,5,1,9,1]
b= a.index(1) . Then b=0

count()
❑ This method is used to count the no.of occurences of an element in a list
Syntax: listname. count(element)
Eg: a=[1,2,3,4,3,5,1,9,1]
b= a.count(1) . Then, b=3

reverse()
❑ This method is used to reverses the elements in a list
Syntax: listname. reverse()
Eg: a=[“C”, ”Python” ,”Java”]
a.reverse()
Now a becomes = [“Java”, ”Python” , ”C”]
DHANYA V,AP IN IT,CEV 16
Downloaded from Ktunotes.in
sort()
❑ This method is used to sort the elements in a list
Syntax: listname. sort()
Eg: a=[“C”, ”Python” ,”Java”]
a.sort() Now a becomes = [“C”, ”Java” , ”Python”]
❑ If we need to sort in descending order:
Syntax: listname. sort(reverse=True)
Eg: a=[“C”, ”Python” ,”Java”]
a.sort(reverse=True) Now a becomes = [“Python”, ”Java” , ”C”]

Sorted()
❑ This method is used to store the sorted elements of a list in another list
Syntax: list2=sorted(list1)
Eg: a=[“C”, ”Python” ,”Java”]
b=sorted(a) b= [“C”, ”Java” , ”Python”]

DHANYA V,AP IN IT,CEV 17


Downloaded from Ktunotes.in
MODULE2-LIST-UNIVERSITY QUESTIONS
2019 SCHEME UNIVQ

Mutable structure : we can add new elements, delete elements or modify


theelements . eg: list , dictionary
Immutable structure : We can’t add, delete or modify elemnts in the data struc
ture . Eg: string , number
A list is an ordered set of values,where each value is identified by an index.
Values are enclosed within square brackets
In a list we can add,delete or modify elements. So it is mutable
Eg: x=[10,20,30]
x.insert(1,100) → insert an element 100 at index 1
Now list becomes : x=[10,100,20,30]
del x[2] → remove element at index 2.
Now list becomes : x=[10,100,30]
x[2] = 90 → replace element at index 2 with 90 Now, x=[10,100,90]
Also we can apply the operations sort, reverse, etc
A tuple is also an ordered set of values, where each value is identified by an
index.
Values are enclosed within parenthesis
But We can’t add ,delete or modify elements in a tuple. So it is immutable.

Ans .
List is an ordered collection of elements.Tuple is also an ordered collection of
elements.
Elements can be: numbers , strings, other lists or tuples etc
Difference
1. List is mutable.ie we can change or delete individual elements
Tuple is immutable. individual elements can’t be modified or deleted

Downloaded from Ktunotes.in


2.List uses [] to enclose elements. Tuple uses ( ) to enclose individual elements.
3.Since tuples are immutable iteration over tuple is faster.

x =[]
f=0
The’n’ elements are read one by one in k
n=input(“enter the no.of elements”)
and each element is appended to the list x
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
s=input(“Enter element to be searched”)
for i in range (0,len(x)): elements of the list are accessed by using
index numbers. index number varies from
if (x[i]==s):
0 to listlength-1
print “Found at index:” ,i
f=1
if(f==0):
print “Not Found”

x =[]
f=0
n=input(“enter the no.of elements”)
print "\n Enter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
s=input(“Enter element to be searched”)
if s in x: we check whether the search value is
print “Found” present in the list using in operator.
else:
print “Not Found”
Downloaded from Ktunotes.in
x =[]
sum=0
n=input(“enter the no.of elements”)
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
for a in x:
s=a*a*a
print s
sum=sum+a
print sum
av=(float)sum/n
print “Average:”,av

x =[]
sum=0
n=input(“enter the no.of elements”)
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
Here ‘a’ stores the elements of the list one by
x.append(k)
one.. cube of each value is calculated ad stored
print “List is:” ,x
in s. sum of cubes are stored in the variable sum.
for a in x:
s=a*a*a
print s
sum=sum+s
print sum

Downloaded from Ktunotes.in


x =[]
s1=s2=0
n=input(“enter the no.of elements”)
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
x.append(k) Here ‘a’ stores the elements of the list one by
print “List is:” ,x one.. If the element is even it is added to s1
for a in x: otherwise added to s2
if(a%2==0):
s1=s1+a
else:
s2=s2+a
print “Sum of even nos:”,s1
print “Sum of odd nos:”,s2

Refer note

m=input("Enter no.of rows: ")


n=input("Enter no.of columns: ")
matrix1=[]
matrix2=[]
matrix3=[]
print "\nEntering the Elements for matrix1....."
for i in range(0,m):
a=[]
for j in range(0,n):
k=input()
a.append(k)
matrix1.append(a)

Downloaded from Ktunotes.in


print "\nEntering the Elements for matrix2....."
for i in range(0,m): • matrix1 is a list in which individual
elements are lists that represent
a=[]
rows of that matrix.
for j in range(0,n):
Eg: matrix1= [ [1,2] , [5,3] ]
k=input() matrix 1 is a 2x2 matrix
a.append(k) 1st row: [1,2]
matrix2.append(a) 2nd row:[5,3]
for i in range(0,m): • Here list ‘a’ is used to store each
row of matrix1.
a=[]
• each row contains n elements.
for j in range(0,n):
• within inner loop the elements of a
k=matrix1[i][j] + matrix2[i][j]
row are entered from keyboard and
a.append(k) append to list ‘a’.
matrix3.append(a) • Then that row (ie list a) is appended
to matrix1
for k in matrix3: • Same method for matrix2
print k

• matrix3 is a list in which individual elements are lists that represent rows of that matrix.
• Here list ‘a’ is used to store each row of matrix3.
• each row contains n elements.
• within inner loop the elements of a row are calculated as the sum of elements in the same row
of matrix1 and matrix2 and the resultant elements are append to list ‘a’.
Eg. row 2 of matrix 3= sum of corresponding elements of row2 of matrix1 and matrix2
• Then that row (ie list a) is appended to matrix3

program to subtract two matrices using list.


k=matrix1[i][j] - matrix2[i][j]
All other steps -same

Downloaded from Ktunotes.in


2015 SCHEME UNIVQ

m=input("Enter no.of rows: ")


n=input("Enter no.of columns: ")
matrix1= matrix2 =[]
print "\nEntering the Elements for matrix1....."
for i in range(0,m): • Transpose is stored in matrix2
a=[] • if order of matrix1 is mxn then order
for j in range(0,n): of transpose matrix will be n x m
k=input() that’s why outer loop varies from 0 to
n-1 and inner loop varies from 0 to m-
a.append(k)
1
matrix1.append(a) • (i,j) th element of matrix2 = (j,i)th
element of matrix1
print "\nCalculating Transpose" • a is used to store each row of matrix2
for i in range(0,n): • In the inner loop elements of each row
a=[] is calculated and appended to list a.
for j in range(0,m): • Then that row is appended to matrix2
a.append(matrix1[j][i])
matrix2.append(a)

for k in matrix2:
print k

x =[]
n=input(“How many names?”)
print "\nEnter the names"
for i in range(1,n+1):
The names in the list are sorted
k=raw_input()
x.append(k)
print “List is:” ,x
Here ‘a’ stores the names in the list one
x.sort() by one..
print “Sorted List:”,x
Then the names are stored in b after
for a in x:
converting in to uppercase .
b=a.upper()
Then these names are displayed
print b

Downloaded from Ktunotes.in


x =x2=[]
n=input(“How many names?”)
print "\nEnter the names"
for i in range(1,n+1): Here ‘a’ stores the names in the list one
by one..
k=raw_input()
Then the names are stored in b after
x.append(k) reversing it. .
print “List is:” ,x Then the name and it’s reverse are
compared .
for a in x:
If palindrome, that name is added to list
b=a[::-1]
x2
if(a==b):
x2.append(a)
print x2

i) data[2] = 89
ii) print data[4][2]
iii) data.remove(56)

Downloaded from Ktunotes.in


i) data[0] = ‘ellipse’
ii) data.append(‘rectangle’)
iii) data.remove(‘square’) data.remove(‘triangle’)

i) scores.insert(0,9) ii) scores.insert(3,9) iii) del scores[4] Or scores.pop(4)

Output :
list : [‘Apple’ , ‘orange’ , ‘grapes’ ]

Downloaded from Ktunotes.in


DICTIONARIES
➢ A Dictionary is an unordered collection of items.
➢ Each item has a key and a corresponding value that is expressed as a pair (key: value).
➢ The (key, value) pairs can be written in any order.

➢ Keys are unique within a Dictionary while values may not be unique.

➢ The values can be of any type but the keys must be of an immutable datatype such as
numbers, strings or tuples.

➢ Dictionary is mutable .We can add new items or change the values of existing items

DICTIONARY OPERATIONS
1. Dictionary Creation
2. Displaying dictionary
3. Dictionary Traversal
4. Updating dictionary elements
5. Deletion of Dictionary elements
6. Membership operations DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
DICTIONARY OPERATIONS

CREATING A DICTIONARY
➢ A Dictionary is created by enclosing the all the items inside curly brackets ({}) separated
by commas
Syntax : Dictionary name={ key1 : value1 , key2 : value2 , key3 : value3 ,……….}

Eg: weekdays= {1: “Sunday” , 2: “Monday “ , 3: “Tuesday “, 4: “Wednesday”}


student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }

color= {5: “Red” , 2: “Blue “ , 3: “Green “, 4: “Orange”}

Employee = {“Name” : “James” , “Designation” : “Programmer” , “Salary” : 60000 }

Dict1 = { } → empty Dictionary

DHANYA V,AP IN IT,CEV 2


Downloaded from Ktunotes.in
CREATING A DICTIONARY BY READING KEYS AND VALUES
FROM KEYBOARD
x ={}
n=input(“enter the no.of elements in the dictionary”)
print "\nEnter the Elements(key, value)"
for i in range(1,n+1):
k=input()
v=input()
x[k] = v
print “Dictionary is:” , x

DHANYA V,AP IN IT,CEV 3


Downloaded from Ktunotes.in
ACCESSING DICTIONARY ITEMS
➢ The elemets are accessed by using keys.
➢ Keys can be used either inside square brackets [] or with the get() method.
➢ In the first method if the key is not found an error is displayed. With get
function, If the key is not found it returns None.
Syntax : dictionary name [key]
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
print student[“RollNo”] will display 10
n= student[“Name”] value of n will be John

DHANYA V,AP IN IT,CEV 4


Downloaded from Ktunotes.in
DISPLAYING A DICTIONARY
print dictionary name
Eg: print student

DICTIONARY LENGTH
➢ The function len is used to find the length of a Dictionary(number of items in the
dictionary)
Syntax: len(Dictionary name)

Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }


l=len(student) l=3

DHANYA V,AP IN IT,CEV 5


Downloaded from Ktunotes.in
DICTIONARY TRAVERSAL
➢ Dictionary Traversal can be done with for loops.
student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }

Here ‘i’ represents each key in the Output: RollNo


for i in student: dictionary.
print i So here keys are displayed one by Name
one mark

for i in student: Here ‘i’ represents each key in the Output: 10


dictionary.
print student[i] John
So here values are displayed one by
one 280

for i in student: Here ‘i’ represents each key in the Output: RollNo : 10
print i, “:” ,student[i] dictionary. Name : John
So here keys and values are
displayed one by one mark : 280

DHANYA V,AP IN IT,CEV 6


Downloaded from Ktunotes.in
ADDING NEW ELEMENTS IN TO DICTIONARY
➢ Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator.
➢ We can add a new item (key-value pair) by using the syntax:
dictionary[key] =value
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
student[“Grade”]=“A”
Now,student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 , ”Grade” : “A”}

MODIFYING ELEMENTS IN A DICTIONARY


➢ We can modify the value corresponding to a key by using the syntax:

dictionary[key] =value
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
student [“mark”] = 290
Now,student = { “RollNo” : 10 , “Name” : “John” , “mark” : 290}

DHANYA V,AP IN IT,CEV 7


Downloaded from Ktunotes.in
DICTIONARY MEMBERSHIP OPERATIONS
➢ We can test if a key is in a dictionary or not using the operators in and not in.
➢ If key is present , in operation returns true else returns false
➢ If key is not present not in operator returns true else returns false
➢ The membership test is only for the keys and not for the values.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

If key 1 is present in the dictionary , display”Present“


if (1 in squares): Otherwise display “Not Present”

print “Present”
else:
Output :Present
print “Not Present”

If key 1 is not present in the dictionary , display”Not


if (1 not in squares):
Present“ Otherwise display “Present”
print “ Not Present”
else:
print “Present”
DHANYA V,AP IN IT,CEV 8
Downloaded from Ktunotes.in
DELETING DICTIONARY ELEMENTS
➢ del statement can be used if we know exactly which element is deleting.
Syntax: del dictionaryname[key] will delete the element corresponding to that key
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
del student[“mark”] will delete the item with key “mark”
student = { “RollNo” : 10 , “Name” : “John” }
dict1 = {1:100 ,2:200,3:300}
del dict1[2]
dict1 = {1:100 ,3:300]
DELETING AN ENTIRE DICTIONARY
Syntax: del dictionaryname
dict1 = {1:100 ,2:200,3:300}
del dict1 will delete the entire dictionary.

DHANYA V,AP IN IT,CEV 9


Downloaded from Ktunotes.in
DICTIONARY METHODS(FUNCTIONS)
✓ Used to perform various dictionary operations

len()
❑ This method is used to find the length of the dictionary(ie no.of items in the dictionary)

Syntax: len(Dictionary name)

Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }


l=len(student) l=3

keys()
❑ This method is used to return a list of keys from the Dictionary .
Syntax: dictionary name. keys()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
a= student. keys()
a= [“RollNo” , “Name” , “mark” ]

DHANYA V,AP IN IT,CEV 10


Downloaded from Ktunotes.in
values()
❑ This method is used to return a list of values from the Dictionary .
Syntax: dictionary name. values()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
a= student. values()
a=[10 , “John” , 280 ]

items()
❑ This method is used to return a list of (key,value) pairs from the Dictionary .
Syntax: dictionary name. items()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
a= student. items()
a= [ (“RollNo” ,10) , (“Name”, “John”) , (“mark” ,280) ]

DHANYA V,AP IN IT,CEV 11


Downloaded from Ktunotes.in
pop()
❑ This method is used to remove a particular item in a Dictionary and returns it’s value.
Syntax: dictionary name. pop(key)
Eg: 1.student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
t= student. pop(“mark”) will delete the item with key “mark” t=280
Now, student = { “RollNo” : 10 , “Name” : “John” }
2.dict1 = {1:100 ,2:200,3:300}
t= dict1.pop(2) will delete the item with key 2 t=200
Now, dict1 = {1:100 ,3:300]

popitem()
❑ This method is used to remove and return an arbitrary item in a Dictionary .[Python2]
Syntax: dictionary name. popitem() Note : We can use del
statement also to delete
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 } an element from
t= student. popitem() dictionary
Note: In Python3, It removes the last item in the dictionary

DHANYA V,AP IN IT,CEV 12


Downloaded from Ktunotes.in
clear()
❑ This method is used to remove all the items in a Dictionary at once.
Syntax: dictionary name. clear()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
student. clear() will remove all the items in the dictionary

sorted()
❑ This method is used to return a sorted list of keys from the Dictionary
Syntax: sorted(dictionary name) [Ascending order sorting]
a = sorted(dictionary name,reverse=True) [descending order sorting]
Eg: student = { 10:”John” , 1: “Ann” , 8: “James” }
a= sorted(student) b=sorted(student , reverse=True)
a= [ 1,8,10] b=[10,8,1]

DHANYA V,AP IN IT,CEV 13


Downloaded from Ktunotes.in
Eg: student = { 8:”John” , 10: “Ann” , 1: “James” }
Display the details in ascending order of roll numbers
a= sorted(student)
for k in a: Output
1 James
print k, student[k] 8 John
10 Ann

Eg: student = { 8:”John” , 10: “Ann” , 1: “James” }


Output
Display the details in descending order of roll numbers
10 Ann
a= sorted(student,reverse=True) 8 John
1 James
for k in a:
print k, student[k]

DHANYA V,AP IN IT,CEV 14


Downloaded from Ktunotes.in
update ()
✓ It is used to update the dictionary with the key - value pairs or with another dictionary.
✓ It inserts key-value pair if it is not present.
✓ It updates the value corresponding to the key if the key-value pair is already present in the
dictionary.

Syntax :
1. dictionary name .update(key = value) – Update with key-value pair
Eg1: data ={“a”:10, “b”:20}
data.update(“c”=30) → data ={“a”:10, “b”:20,”c”:30}
Eg2: data ={“a”:10, “b”:20}
data.update(“b”=30) → data ={“a”:10, “b”:30}
2. dictionary name.update(dictionary2) –Update with dictionary2
Eg1: data ={“a”:10, “b”:20} data2={ 5 : 50 , 1:100}
data.update(data2) → data ={“a”:10, “b”:20,” 5:50 ,1:100}
DHANYA V,AP IN IT,CEV 15
Downloaded from Ktunotes.in
DICTIONARY COPYING
1.Using Assignment operator(=) Here d1 and d2 represent same memory locations
d1={1:1,2:4 ,3:9} where the dictionary values are stored. So when
d2=d1 one variable is updated the change will be reflected
d1[4] = 16 in other variable also.
print “d1=“, d1 , “\nd2 =“ ,d2 Output
d1={1:1,2:4 ,3:9 ,4:16}
d2={1:1,2:4 ,3:9 ,4:16}

2.Using copy() function Here a copy of dictionary values are stored in d2(in
d1={1:1, 2:4 , 3:9} different memory locations) So when one variable is
d2=d1.copy() updated it will not affect the other variable.
d1[4] = 16 Output
print “d1=“, d1 , “\nd2 =“ ,d2 d1={1:1,2:4 ,3:9 ,4:16}
d2={1:1, 2:4 , 3:9 }

DHANYA V,AP IN IT,CEV 16


Downloaded from Ktunotes.in
2019 SCHEME UNIV Q- DICTIONARIES

Suppose name is used as key(Assume that names are unique) . So we need to sort in asc
order of keys for loop executes 5 times. so we can enter detais of 5
student={} students .
for i in range(1,6):
student[s]= r means the key value pair(s,r) is inserted
r= input("enter roll no:") in the dictionary student. ie name is used as key and
s=raw_input("enter name:") roll no as value corresponding to that key
student[s]=r
print student The keys of dictionary(student) are sorted and
t=sorted(student) stored in the list ‘t’
for i in t:
Traverse list ‘t’ . here ‘i’represents each element in
print i, student[i] the list (ie keys in the dictioary in sorted order)

we display i and student[i] ie key (name) and value


(roll no)

List : ordered collection of items.It is mutable ie we can change a list


(insert,delete,update elements)
Tuple: ordered collection of items. It is Immutable ie we can’t change a tuple

Dictionary: unordered collection of items.Each item has a key and a


corresponding value that is expressed as a pair (key: value.
When you want to use immutable ordered collection of elements use tuple.
When you want to use mutable ordered collection of elements use list
when you want to use mutable unordered collection of elements and you have a
unique set of keys that map to values use dictionary

Downloaded from Ktunotes.in


(Sparse matrix is is a matrix for which majority of the elements are zero. We
waste a lot of memory space when we express it with a normal 2-dimensional
array.So we aim to store only the non-zero elements)

A Dictionary is created by enclosing the all the items inside curly brackets ({})
separated by commas
Syntax : Dictionary name={ key1 : value1 , key2 : value2 , key3 : value3 ,……….}
Eg: weekdays= {1: “Sunday” , 2: “Monday “ , 3: “Tuesday “, 4: “Wednesday”}

To read a sparse matrix using dictionary we read the non zero element and it’s row
and column indices
m=input("Enter no.of rows of sparse mat: ")
n=input("Enter no.of columns: ")
matrix1=[]
print "\nEntering the Elements for sparse matrix1....."
for i in range(0,m):
The non-zero elements are added to the
a=[] dictionary .
Key : tuple representing row index and column
for j in range(0,n): index of nonzero value.
value : The nonzero value
k=input()
a.append(k) For eg: if row and col index of nonzero value 7
are 1 and 3 resp: then the dictionary entry
matrix1.append(a) corresponding to that non zer value is (1,3) : 7

D={}
for i in range(0,m):
for j in range(0,n):
if(matrix1[i][j] !=0):
D[(i,j)] = matrix1[i][j]
Print “Sparse Matrix in Dictionary representation:” ,D

Downloaded from Ktunotes.in


➢ A Dictionary is an unordered collection of items.
➢ Each item has a key and a corresponding value that is expressed as a pair (key:
value).
➢ Keys are unique within a Dictionary while values may not be unique.

➢ The values can be of any type but the keys must be of an immutable datatype
such as numbers, strings or tuples.
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
dictionar operations (Briefly explain any 5)
1. Dictionary Creation 2. Displaying dictionary
3. Dictionary Traversal 4. Updating dictionary elements
5.Deletion of Dictionary elements 6.Membership operations

2015 SCHEME REPEATED UNIV Q

Refer Note.

keys(),values().items(),clear(),pop() etc

Suppose name is used as key (Assume that names are unique) . So we need to sort in asc
order of keys
D={}
for i in range(1,6):
s=raw_input("enter name:")
p= input("enter phone no:")
D[s]=p
print D
t=sorted(D)
for k in t:
print k, D [k]

Downloaded from Ktunotes.in


a) data[“b”] = -data[“b”] The elemets of dictionary are accessed by using keys.
b) data[“c”] = 56
dictionaryname[key] will give the value corresponding to
c) del data[“a”] or data.pop(“a”)
that key

Refer Note.

has_key : Used to check whether a key is present in the dictionary.This method


returns true if specified key is present in the dictionary, else returns false.

Syntax: dictionary.has_key(key)

Eg: Data = { 'A': 'Apple', 'B': 'Banana', 'C': 'Cherry' }


print (Data.has_key('B')) output : True

i) farm[“Ducks”] = 8
ii) print len(farm)
iii) del farm[“Cows”] or farm.pop(“Cows”)

Downloaded from Ktunotes.in


Here newstudent and student
represent same memory locations
where the dictionary values are
stored. So when one variable is
updated the change will be
reflected in other variable also.
{‘John’ :50 , ‘Tom’ : 60 , ‘Nina’ : 82 , ‘Tom’ : 45 }

{‘John’ :50 , ‘Tom’ : 60 , ‘Nina’ : 82 , ‘Tom’ : 45 }

stock ={}
stock[‘pencil’]=400
stock[‘pen’]=1000
stock[‘eraser’]=200
stock[‘ink’]=50
i) print stock
ii) del stock[‘ink’]
print stock
iii) A Dictionary is an unordered collection of items.Each item has a key and a
corresponding value that is expressed as a pair (key: value).
The (key,value) pairs can be written in any order.
Keys are unique within a Dictionary while values may not be unique.
The values can be of any type but the keys must be of an immutable datatype
such as numbers, strings or tuples.
• To find no. of key-value pairs(no.of elements in the dictionary) , we can use len(stock)
• Keys : pencil,pen,eraser,ink
• To display a list of keys , use the statement print stock.keys()

Downloaded from Ktunotes.in


stock repr as dictioary. book title is used
books = {"c":100,"c++":200,"python":150} as key and no of copies that book is used
while (True): as value

print "Menu\n 1.Add books\n 2.Sell books\n 3.Exit" Display choice menu

a=input("Enter your choice:")


For adding a new book in the stock, enter
if a==1:
title and no of copies of that book.
t=raw_input("Enter title:")
c=input("Enter no.of copies:") If the book is already present in the stock, no.
of copies are incremented by c.
if t in books:
Since title is used as key and no of copies as
books[t]=books[t]+c value, books[t] means no of copies of the book
with title t
else:
If the book is not already present in the stock,
books[t]=c
the title and it’s no of copies are added as a
print books new key,value pair

elif a==2: For selling ,first we enter title and no of copies


t=raw_input("Enter title:") of that book. requested by a customer
c=input("Enter no.of copies:") Then check whether the book requested by
if t not in books: customer is already present in the stock.
print "\n not available!!!! \n"
If present next we check whether the requested
elif c>books[t]:
no of copies are available in the stock.
books[t]=0
If req no of copies ( c) > no of copies already in
else: the stock (books[t]) then no of copies in the stock
becomes 0. Because all the copies will be given to
books[t]=books[t]-c customer
print books
If req no of copies ( c) <= no of copies already in
elif a==3: the stock (books[t]) then no of copies in the stock
break is decremented by ‘c’ because ‘c’ copies will be
else: given to customer
print "\n\tEnter valid choice(1/2/3)!!!!"

Downloaded from Ktunotes.in


2015 SCHEME OTHER UNIV Q

same pattern qn as book shop details

Data={}
n=input(“Enter no.of account holders:”)
for i in range(1,n+1):
a=input("enter account no:")
b= input("enter account balance:")
Data[a]=b

while (True):
print "Menu\n 1.Deposit\n 2.Withdraw\n 3.Exit"
c=input("Enter your choice:")
if c==1:
ac=input("Enter account no:")
amt=input("Enter amount to deposit:")
Data[ac] =Data[ac]+amt
print Data
elif c==2:
ac=input("Enter account no:")
amt=input("Enter amount to withdraw:")
if amt>books[ac]:
print “Insufficient Balance!!”
else:
Data[ac] =Data[ac]-amt
print Data
elif c==3:
break
else:
print "\n\tEnter valid choice(1/2/3)!!!!"

Downloaded from Ktunotes.in


Q

same pattern qn as book shop details

items = {"Laptop":100,"MobilePhone":200,"Camera":150}
while (True):
print "Menu\n 1.Add Items\n 2.Delete Items\n 3.Exit"
a=input("Enter your choice:")
if a==1:
i=raw_input("Enter item:")
n=input("Enter no.of units:")
items[i]=items[i]+n
print items
elif a==2:
i=raw_input("Enter item:")
n=input("Enter no.of units:")
if n>items[i]:
items[i]=0
else:
items[i]= items[i]-n
print items
elif a==3:
break
else:
print "\n\tEnter valid choice(1/2/3)!!!!"

Dictionary methods : refer Note

Downloaded from Ktunotes.in


s=raw_input("Enter the string") Eg: s=”hello are u there hello how are u”
x=s.split(" ") x=[‘hello’,’are’,’u’,’there’,’hello’,’how’,’are’,’u’]
print x d={}
d={} w=hello d[‘hello’]=1
for w in x: w=are d[‘are’]=1
if w not in d: w= u d[‘u] =1
d[w]=1 w=there d[‘there’]=1
else: w=hello d[‘hello’]=1+1=2
d[w]=d[w]+1 w=how d[‘how’]=1
print d w=’are’ d[‘are’]=1+1=2
w=’u’ d[‘u’]=1+1=2
d={‘hello’ :2, ‘are’:2, ‘a’ :2 ,’there’:1,…..}

Ans) Using copy() function


d1={1:1, 2:4 , 3:9}
d2=d1.copy()
d2={1:1, 2:4 , 3:9}
When d1 is modified it will not affect d2
d1[4] = 16
print “d1=“, d1 , “\nd2 =“ ,d2
Then : d1={1:1, 2:4 , 3:9 , 4:16} d2={1:1, 2:4 , 3:9}

Key value To print keys


name John print Dict.keys()
age 25 To print values
salary 28000 print Dict.values()

Downloaded from Ktunotes.in

You might also like