[go: up one dir, main page]

0% found this document useful (0 votes)
35 views25 pages

Notes - Strings,List,Tuple,Dictionary

The document provides an overview of strings and lists in Python, detailing their properties, operations, and built-in methods. It covers string manipulation techniques such as concatenation, slicing, and various string methods, as well as list creation, indexing, and operations like concatenation and membership testing. The document serves as a comprehensive guide for understanding and utilizing strings and lists in Python programming.

Uploaded by

revathi25
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)
35 views25 pages

Notes - Strings,List,Tuple,Dictionary

The document provides an overview of strings and lists in Python, detailing their properties, operations, and built-in methods. It covers string manipulation techniques such as concatenation, slicing, and various string methods, as well as list creation, indexing, and operations like concatenation and membership testing. The document serves as a comprehensive guide for understanding and utilizing strings and lists in Python programming.

Uploaded by

revathi25
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/ 25

STRINGS

• In python strings are characters enclosed in single, double or triple


quotes.
• Each character has a unique position id/index
• The indexing of a string starts from 0 to length -1 in forward direction
• from -1 to –length in the backward direction.
Traversing
Traversing refers to iterating through the elements of a string , one
character at a time.
str=”hello”
for ch in str: (we use the membership operator in to traverse)
print(ch)
The output will be hello
String Operators
(i) Concatenation (+) : Creates a new string by joining two strings
Ex: “good” + “morning” will give output as goodmorning
but both the operand should be of string type. Ex : 123 + “abc” will
produce an error because we cannot add a integer to a string.
(ii) Replication Operator (*) : It takes a string and a number as operand and
creates a new string that is a number of repetitions of the string operand.
Ex: ‘and’ * 3 will give andandand
4 * ‘&’ will give &&&&
(iii) Membership Operators :
in : returns True if a character or a substring exists in the given string,
otherwise returns False.
not in : returns True if a character or a substring does not exists in the
given string, otherwise returns False.
Ex: “ind” in “india” will give True
“apple” not in “pineapple” will give False. It is case sensitive
Hell not in hello will give True
(iv) Comparison Operators:. Python compares two strings through
relational operators using character by
character of their Unicode values.
CHARACTERS UNICODE VALUES
‘0’ to ‘9’ 48 to 57
‘A to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

Ex: “best” == “best” will return True


“A” != “a” will return True
“good” < “Good” will return False as g ordinal value is greater than G.

ord() : takes as single character and returns the corresponding ordinal


Unicode value
Ex: ord(‘B’) gives 66
ord(‘3’) gives 51
chr(): takes the ordinal value in integer form and returns the charcter
corresponding to thar ordinal value.
Ex: chr(100) will give ‘d’
chr(65) will give ‘A’
len() : this function returns the number of character in the string
Ex: str1=”Collection”
print(len(str1)) will give 10 as result
STRING SLICES
Basic syntax : sting_var[start:end:step]
• end is not inclusive, by default step value is 1.
• we can slice both using positive and negative index
• if the start index is not specified, by default it starts from 0
• if end value is not specified it will traverse till the length of the string.
Ex: str = “programming”
0 1 2 3 4 5 6 7 8 9 10
p r o g r a m m i n g
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String Slice Output Indexes Printed
str[6] ‘m’ 6
str[0:4] ‘prog’ 0,1,2,3
str[3:6] ‘gra’ 3,4,5
str[ : 3] ‘pro’ 0,1,2
str[-5:-2] ‘mmi’ -5,-4,-3
str[5:] ‘amming’ 5,6,7,8,9
str[1:8:2] ‘rgam’ 1,3,5,7
for any number n
str[n:]+str[:n]
str[2:]+str[:2] or ‘programming’ will produce the original
str[5:],str[:5] string
str[: : -1] ‘gnimmargorp’ reverses the string
str[3:15] last index is out of range
‘gramming’ so it will print till the
length of the string
str[15:25] ‘‘ empty string, as both
start and end are out of
range.

Built-In String Manipulation Methods


String Methods Output (returns) Example
string.capitalize( ) • Returns a copy of the string >>a = “hello”
with its first character >>b=a.capitalize()
capitalized >>b
‘Hello’
string.find(sub,[,star • Returns the lowest index in
t[,end]]) the string where the >> wd = “worldandworld”
substring is found within the >>s=”and”
given range of start and end. >>wd.find(s)
• If start and end is not given 5
it takes the entire string >>wd.find(s,0,4)
• Returns -1 if substring is not -1
found
string.title() It returns the copy of te string >>s=computer SCIENCE
by converting all the first >>s.title()
character of each word in >>Computer Science
uppercase and all other
chars in lowercase
string.isalnum() • Returns True if the >>str1=’hello123’
characters in the string are >>str2 = ‘123456’
alphanumeric, False >>str1.isalnum()
otherwise True
>>str2.isalnum()
False
string.isalpha() • Returns True if the string >>str1=’hello123’
are alphabetic, False >>str2 = ‘asdfg’
otherwise >>str1.isalpha()
False
>>str2.isalpha()
True
string.isdigit() • Returns True if all the >>str1=’123456’
characters in the string are >>str2 = ‘12asdfg’
digits, False otherwise >>str1.isdigit()
True
>>str2.isdigit()
False
string.islower() • Returns True if the >>str1=’hello’
characters in the string are >>str2 = ‘Apple’
lowercase, False otherwise >>str1.islower()
True
>>str2.islower()
False
string.isupper() • Returns True if the >>str1=’GOOD’
characters in the string are >>str2 = ‘Apple’
uppercase, False otherwise >>str1.isupper()
True
>>str2.isupper()
False

string.isspace() • Returns True if there are >>str1=” “


only whitespace characters >>str2 = “12 4”
in the string. >>str1.isspace()
True
>>str2.isspace()
False
string.lower() • Returns a copy of the string >>str1=’ ALPHABETS’
converted to lowercase >>q=str1.lower()
>>q
alphabets
string.upper() • Returns a copy of the string >>str1=’ functions’
converted to uppercase >>u=str1.upper()s
>>u
FUNCTIONS
string.count() ● Returns the number of >>s=”abcdabcdabcd’
substring in a sting >>c=s.count(‘ab’)
● Syntax: >>print(c)
str.count(substr,start,end) >>3
● Start and end are optional >>c=s.count(‘ab’,0,3)
>>c
>>1
string.index() ● It returns the lowest index >>s=”abcdabcdabcd’
where the specified substring >>c=s.index(‘ab’)
is found. >>c
● If the substring is not found >>0
Then it raises a ValueError >>c=s.index(‘ab’,2,8)
>>c
>>4
string.strip() ● Returns a copy of the string >>s=” Hello “
by removing the leading and >>s=s.strip()
trailing white spaces. >>s
● If arguments are passed then >>Hello
characters that we pass will >>s=”Hello.com“
be removed >>s=s.strip(“mco”)
>>s
>>Hello.
(combinations of chars can be
removed mco can be
com,ocm,cmo,etc)
string.lstrip() ● Returns a copy of the string >>s=” Hello“
by removing the leading >>s=len(s)
white spaces. >>s
>>7
>>s=len(s.lstrip())
>>s
>>5
string.rstrip() ● Returns a copy of the string >>s=”Hello “
by removing the trailing >>s=len(s)
white spaces. >>s
>>7
>>s=len(s.rstrip())
>>s
>>5
string.replace() ● Returns a copy of the string >>s=’i like java’
with all occurrences of >>s1=s.replace(‘java’,’python’)
substring old replaced by >>s1
new string >>i like python
● Syntax:
str.replace(old,new)
str.join() ● It joins a string/character >>a=’#’.join(“hello”)
after each member >>a
(List/Tuple/String) of the >>”h#e#l#l#o”
sequence >>b=’@’.join([“abc”,”def”])
● If it is a string,then the >>b
character/str is inserted >>”abc@def”
after every character. >>c=”$$”.join((1,”apple”,”bat”)
● If it is a tuple/list then it is >>Error bcoz the sequence should
inserted after each element not contain only strings
● It also returns
str.split() ● It splits a string based on >>s=”my name is arun”.split()
space(by default) or using >>s
the given str/char and >>[“my”,”name”,”is”,”arun”]
returns it as a list >>s1=”my name is arun”.split(‘a’)
>>s1
>>[“my n”,”me is “,”run”]
str.partition() ● It takes a string and split >>txt=”i am fond of music”
based on the separator and >>d=txt.partition(“of”)
returns a tuple containing 3 >>d
items (part before >>(‘i am fond’,’of’,’music’)
string,separator,part after >>x=txt.partition(“and”)
the separator) >>x
● If the separator is not >>(‘i am fond of music’,’ ‘ , ‘ ‘ )
present in the string the
whole string is taken as the
first element,the the second
and third will be an empty
string.

LISTS
• Lists are sequences that store a list of values of any datatype.
• Lists are Mutable i.e we can change the elements of a list in place
• It is defined inside square brackets [ ]
• Ex:
[] empty list
[5,10,15] integer list
[‘aba’,1,3.2,’aa’,32] mixed list
[ 10,20,[‘a’,’b’,’c’],30,40] Nested list (list
inside a list)
CREATING A LIST
1. L1=[1,2,3,4,5,6,7,8]
2. L2 = list( ) or L2 = [ ] #creates an empty list
3. L3= list(‘Goodday’) will create a list L3=[‘G’,’o’,’o’,’d’,’d’,’a’,’y’]
4. L4= list(input(“Enter list elements:”))
Enter list items: 98765 will create a list L4=[‘9’,’8’,’7’,’6’,’5’]
(or) Enter list items: aeiou will create a list L4=[‘a’,’e’,’i’,’o’,’u’]
Here everything is taken as a string.
5. L5= eval(input(“Enter the list items:”))
Enter the list items: [11,12,13,14,55] # we should enter the elements
# inside the square brackets.

eval( ) function
• Used to evaluate and return the result of an expression given as string.
Ex:
>>a= eval(‘30’+’45’)
>>print(a) - will give 75 as result
• It will interpret the values given as the intended types
Ex:
x = eval(input(“Enter a value”))
if (i) x is given 10 it is taken as an integer
(ii) x is given 34.2 it is taken as float
(iii) x is given [12,13,14] it is taken as list etc
Indexing in list
Similar to strings, has both forward and backward indexing.
list1= [11,21,34,41,58,60,73,89,94]

0 1 2 3 4 5 6 7 8
11 21 34 41 58 60 73 89 94
-9 -8 -7 -6 -5 -4 -3 -2 -1

Traversing in a list
Traversing a list means accessing and processing each element in the
list. That’s why traversal sometimes call as looping over a sequence.
Ex:
(i) S= [ ‘c’,’o’,’m’,p’,’a’,’r’,’e’]
for x in S:
print(x,end=” “) #will print the result as c o m p a r e
here x will be assigned directly to the list elements one at a time.
(ii) If we need the indexes of the elements to access them ,then we the
range
function.
for x in range(len(S)):
print (x,S[x]) # will print the same result as c o m p a r e

List Operations
(i) Concatenation (+) : Creates a new list by joining two lists
Ex: a= [1,3,5] b = [2,4,6]
c=a+b
will create list c =[1,2,3,4,5,6]
but both the operand should be of list types. We cannot add a list to a
number, complex number or a string.
(ii) Replication Operator (*) : It takes a list and replicate it the specified
number
of times.
Ex: lst1 = [2,3,4]
>>lst1*4
will give result [2,3,4,2,3,4,2,3,4]
(iii) Membership Operators :
in : returns True if a element is present in the list,
otherwise returns False.
not in : returns True if a element is not present in the list ,
otherwise returns False.
Ex: 2 in [11,2,3,4] will give True
5 not in [55,65,5,75,85] will give False

(iv) Comparison of Lists


• Python compares individual elements of lists in lexicographical order.
• Two sequences compared should be of the same and comparable type.
• It produces result True or False by comparing corresponding elements, if
corresponding elements are equal , it goes to the next element, and so
on, until it finds elements that differ.

[1,2,3,4]==[1,2,3,4] True Both the list are equal


[1,2,3[4,5]] > [1,2,3,4,5] Produces error because when it comes to
index 3 the first list
contains a nested list[4,5]
but the second list
contains a integer
element(4).So it is
incomparable, we cannot
compare a list with a
integer.
[10,20,30,45] < [10,20,30,50] True First three elements are
same but the last
element of the second list
is greater than the first
list .

Accessing Individual Elements


The individual elements of a list are accessed through their indexes.
alpha = [1,2,’aa’,4,’bb’,5]
alpha[4] will give ‘bb’ alpha[1] will give 2.
we will get an IndexError if we try to give a index out of range Ex:alpha[10]
Difference from Strings.
Strings are Immutable but lists are Mutable. We can change the value of a
element in a list in place by using its index.
>> list1=[1,2,3,’aa’,5]
>>list1[3] = 4
>>list1
>>[1,2,3,4,5]
SLICING THE LIST
L = [start:stop]
creates a list slice out of list L with elements falling between indexes start and
stop, not excluding stop. Step value by default is 1.We can also give step value
as [start:stop:step].
listA=[11,22,33,44,55,66,77,88,99]
0 1 2 3 4 5 6 7 8
11 22 33 44 55 66 77 88 99
-9 -8 -7 -6 -5 -4 -3 -2 -1

List Slice Output Indexes Printed


listA[2:6] [33,44,55,66] 2,3,4,5
listA[1:8:2] [22,44,66,88] 1,3,5,7
listA[3:25] [44,55,66,77,88,99] Since the stop value is out of
bound it will prints from index 3
till the end of the list
listA[-20:4] [11,22] Since the start value is out of
bound it prints from the start of
list till index 3.
listA[10:30] [] Both the limits are out of bound
so prints a empty list
listA[2:9:2] [33,55,77,99] 2,4,6,8 (step value 2)
listA[ :5:2] [11,33,55] 0,2,4 (start value is skipped ,so
starts from index 0)
listA[ 4: ] [55,66,77,88,99] 4,5,6,7,8 (end value is skipped,so
prints till the end of the list i.e
len-1)
listA[: : 3] [11,44,77] 0,3,7 (no start and end, so takes
the entire list ) Step value is 3.
listA[::-1] [99,88,77,66,55,44,33,22,11] Reverses the list
Using Slice for List Modification
(i) We can modify the value of a element in a list by using its index.
F =[“apple”,”orange”,”papaya”,100,220,300,”grapes”]
>>F[3]=”fig”
>>F
>>[“apple”,”orange”,”papaya”,”fig”,220,300,”grapes”]
(ii) Using slices
F =[“apple”,”orange”,”papaya”,100,220,300,”grapes”]
>>F[3:6] = [“banana”,”mango”,”fig”]
>>F
[“apple”,”orange”,”papaya”,“banana”,”mango”,”fig”,”grapes”]

nos=[10,20,30,40,50]
>>nos[3: ] = “54321”
>>nos
[10, 20, 30, '5', '4', '3', '2', '1']

>>nos[4:10] = “abcd” #even when index 10 is out of bound it will not


#produce error,it just keep on adding till the end.
>>nos
[10, 20, 30, 200, 'a', 'b', 'c', 'd']

>>nos[10:20] = “12345” #when both index are out of bound just


adds
# elements to the end of the list
>>nos
[10, 20, 30, 200, 'a', 'b', 'c', 'd', '1', '2', '3', '4', '5']
Slicing for modification will always take a sequence, does not accept individual
element
Ex: nos[2:4] =345
will produce an error, because 345 is an integer not a sequence.

Operations on a List
(i) Adding elements to a list
The append() method is used to add a single element to the
end of the list.
Syntax: listobject.append(item)
L=[12,43,56,89]
>>L.append(32)
>>L
[12,43,56,89,32]
(ii) Updating elements in a list
>> list1=[1,2,3,’aa’,5]
>>list1[3] = 4
>>list1
>>[1,2,3,4,5]
(ii) Deleting elements from a list
a. del statement
• The del statement can be used to remove an individual item, or
remove all items identified by a slice.
• It takes the index of the elements to delete it.
A=[10,20,30,40,50,60,70,80,90,100]
>>del A[4]
>>A
[10,20,30,40,60,70,80,90,100], # 50 is the element present in index 4

A=[10,20,30,40,50,60,70,80,90,100]
>>del A[3:6]
>>A
[10,20,30,70,80,90,100]

b. pop() method
It removes an individual element and returns it.
Syntax: lstobject .pop(index)
Ex:
L1=[11,23,45,66,88,46,89]
>>L1.pop(4)
88
>>L1
[11,23,45,66,46,89]
This method is useful when we want to restore the element that is
been deleted for later use
Ex: x1 = L1.pop(2) #element 45 will be stored in x1
Difference between del statement and pop()
Del statement Pop() method
It can remove a single element or a list The pop() method removes only a single
slice from a list element
It does not return the deleted element, It returns the deleted element. So we
so item once deleted cannot be can assign it to a variable and retrieve
retrieved it later if needed.

Making Copies of List


Method 1:
x = [10,20,34,56,78]
y=x
Here, y is just an alias to x ,i.e y label points to the same memory location
where x label is pointing to.
10 20 34 56 78

So, any changes made to x will also be reflected to y and vice versa
Ex: x[3] = 72
>>x
[10,20,34,72,78]
>>y
[10,20,34,72,78]
Method 2:
x = [1,2,3,4,5]
>>y = list(x)
>>x[2]=’A’
>>x
[1,2,’A’,4,5]
>>y
[1,2,3,4,5]
Here two independent copies of list are made. So changes to one list will not
affect the other.
10 20 ‘A’ 56 78

10 20 34 56 78
LIST FUNCTIONS & METHODS
METHOD EXPLANATION EXAMPLE RETUR
N
(YES/N
O)
index() • Returns the first Ex 1: Yes
method index of the first A1=[13,14,15,16,17,16,18]
matched item from >>A1.index[16]
the list 3
Syntax:
listobject.index(item) Ex 2:
• If the element is not >> C = A1.index[14]
found then it raises >>C
an exception - value 1
error

append() • Adds an item to the Ex1: B1=[‘a’,’e’,’i’,’o’] No


method end of the list >>B1.append(‘u’)
Syntax: >>B1
listobject.append(item) [‘a’,’e’,’i’,’o’,’u’]
• Does not create a new
list just modifies the Ex 2: T1=[1,3,5,7]
original list >>T1.append([2,3,4])
>>T1
[1,3,5,7,[2,3,4])
extend() • Adds multiple Ex1 : S = [1,2,3,4,5] No
method elements to the end of X = [5,6,7,8]
the list.It always >> S.extend(X)
accepts a sequence >> S
(list,tuple,string) as [1,2,3,4,5,5,6,7,8]
argument
Syntax: Ex 2: T1=[1,3,5,7]
listobject.append(<seq>) >>T1.extend([2,3,4])
• It also modifies the >>T1
existing list and does [1,3,5,7,2,3,4]
not return
insert() • Inserts an element at Ex 1: M = [10,’a’,20,30] No
method a given position. >>M.insert(3,’b’)
Syntax: >>M
listobject.insert(index,ite [10,’a’,20,’b’,30]
m)
• It returns no value.
pop() • It removes an Ex 1: List1=[‘x’,’y’,’z’,’q’] Yes
method individual element by >>e1=List1.pop(2)
taking its index. >>e1
• It also returns the ‘z’
element. >>List1
Syntax: [‘x’,’y’,’q’]
listobject .pop(index)
• If no index specified Ex 2:
then it will remove the >>List1.pop()
last element from the ‘ q’
list. >>List1
• It raises an exception [‘x’,’y’]
if the list is already
empty.
remove() • It removes the first Ex 1: No
method occurrence of given lst1= [ ‘a’,’s’,’d’,’f’,’g,’,h’]
item from the list. >>lst1.remove(‘f’)
• Does not return >>lst1
anything. [‘a’,’s’,’d’,’g,’,h’]
• Reports an error if no
such item is present
in the list.
Syntax:
listobject.remove(value)

clear() • Removes all the Ex: No


method element from the list L = [1,2,3]
and the list becomes >>L.clear()
empty >>L
• It removes only the []
elements, so the list
object will exist as an
empty list
Syntax:
listobject.clear()
count() • Returns the count of Ex 1: Yes
method the item passed as S1= [1,2,3,2,2,4,5,2,7]
argument. >>Val = S1.count(2)
• If the item is not >>Val
present in the list, it 4
returns zero. >>S1.count(6)
Syntax: 0
listobject.count(item)
reverse() • Reverses the items of Ex: No
method the list. M=[1,2,3,4,5,6]
• It does not create a >>M.reverse()
new list, it makes >>M
changes to the [6,5,4,3,2,1]
existing list.
• Takes no argument
and does not return
anything
sort() • Sorts the items of the Ex 1: No
method list, by default T1= [ ‘a’,’c’,’e’,’b’,’d’]
ascending order. >>T1.sort()
• It does not create a [‘a’,’b’,’c’,’d’,’e’]
new list, it makes
changes to the Ex 2:
existing list. To sort in descending order
• Does not return T2 = [14,3,6,2,6,32]
anything. >>T2.sort(reverse=True)
>>T2
[32,14,6,6,3,2]
sorted() ● Sorts the items of the >>val=[2,6,3,8,9] Yes
method list, and returns the >>sval = sorted(val)
list in ascending order >>sval
by default. >>[2,3,6,8,9]
>>sval=sorted(val,reverse=True
)
>>sval
>>[9,8,6,3,2]
max(list) ● Takes a list and >>max([2,7,3,6,0] Yes
min(list) returns the >>6
sum(list) maximum,minimum >>L=[‘t’,’e’,’a’,’d’]
and sum of elements >>min(L)
of the list. >>’a’
● All elements should >>s= sum([2,3,4,5])
be of same type. >>s
>>14

TUPLES
• Tuples are sequences that are used to store values of any type.
• Tuples are Immutable i.e we cannot change the elements of tuple in
place
• They are depicted through Parentheses Ex: (1,2,3,4)

• Creating a Tuple
Empty Tuple T1=tuple() or T1=( )
Single element tuple T2=(4, ) or T2 =4,
Long Tuples T3=(2,7,4,6,7,33,2)
Nested Tuples T4= (22,44,66,1,(3,4,5),5)
Creating tuple from a T5=tuple(“hello”)
Sting >>T5
(‘h’,’e’,’l’,’l’,’o’)
Creating a tuple from a L=[2,3,4,5,6]
list T6=tuple(L)
>>T6
(2,3,4,5,6)
Creating a tuple during T7=tuple(input(“Enter tuple items:”))
runtime >>Enter tuple items: 34567
>>T7
(‘3’,’4’,’5’,’6’,’7’) #created as string type
(or)
T7=eval(input(“Enter tuple items:”))
>>Enter tuple items: (3,4,’a’,(1,2,),4)
>>T7
(3,4,’a’,(1,2,),4)

2. Indexing in tuple
Similar to strings and list , has both forward and backward indexing.
tup1= (11,21,34,41,58,60,73,89,94)

0 1 2 3 4 5 6 7 8
11 21 34 41 58 60 73 89 94
-9 -8 -7 -6 -5 -4 -3 -2 -1

3. Accessing Individual Elements


The individual elements of a tuple are accessed through their indexes.
sqr = (1,4,9,16,25,’aa’,’bb’)
>>sqr[3] will display 16
>>sqr[-2] will display ‘aa’

3. Traversing in a tuple
Traversing in a tuple means accessing and processing each element in
the tuple.
Ex:
(i) M= (‘hello’,1,2,3)
for x in M:
print(x,end=” “) #will print the result as ‘hello’ 1 2 3
here x will be assigned directly to the tuple elements one at a time.
(ii) If we need the indexes of the elements to access them ,then we the
range
function.
for y in range(len(M)):
print (M[y]) #will print the result as ‘hello’ 1 2 3
4.Tuple Operations
(i) Joining Tuples : Creates a new tuple by joining two or more tuples.
Ex: a= (1,2,3) b = (4,5,3) c=(7,8,9)
d=a+b+c
will create a tuple d =(1,2,3,3,4,5,7,8,9)
but both the operand should be of tuple types. We cannot add a tuple to a
number, complex number, string or list.
(ii) Replication Operator (*) : It takes a tuple and replicate it the specified
number of times.
Ex: tup1 = (5,7,8)
>>tup1*3
will give result (5,7,8,5,7,8,5,7,8)
(iii) Membership Operators :
in : returns True if a element is present in the tuple,
otherwise returns False.
not in : returns True if a element is not present in the tuple ,
otherwise returns False.
Ex: 5 in (11,2,3,4) will give False
(iv) Comparing Tuples
• To compare two tuples we use the comparison operators <,>,==,!=
• It produces result True or False by comparing corresponding elements, if
corresponding elements are equal , it goes to the next element, and so
on, until it finds elements that differ.
A=(1,2,3) B=(1,2,3) True Both the list are equal
A==B
A=(1,2,3) B=(‘1’,’2’,3) False One tuple contains
A==B integers and another
tuple contains strings
C=(2.0,3.0) D=(2.0,3.7) False First element is same but
C>D the last element of the
second list is greater
than the first list .
5. Unpacking Tuples
• Creating a tuple from a set of values is called packing
• Creating individual values from a tuple’s elements is called Unpacking
Syntax:
<var1>,<var2>,<var3>=tuple
The number of variables in the left side of assignment must match the
number of elements in the tuple.
Ex1: T=(1,’hi,3,’hello’)
a,b,c,d = T
>>print(a,b,c,d)
• ‘hi’ 3 ‘hello’
Ex 2: L1=[10,20,30]
T=(200,300)
L1[0],L1[2] = T
>>L1
[200,20,300] #the first and the third list item is replaced with the
#elements of the tuple
6. Deleting Tuples
• As tuples are immutable, which means that the individual
elements of a tuple cannot be deleted.
T1=(21,35,42,51,62,78)
>>del T1[2]
• will produce a trace back error message stating that ‘Tuple’ object
does not support deletion.
• But we can delete a complete tuple with del statement.
Syntax: del <tuple_name>
del T1 # will delete the entire tuple object
TUPLE FUNCTIONS & METHODS
METHOD EXPLANATION EXAMPLE RETURN
(YES/NO)
len () • Returns the length of Ex 1: Yes
method the tuple. T1=(2,3,4,5,6,7)
Syntax: len(<tuple>) >>len(T1)
• Take tuple name as 6
argument and returns
an integer.

max() • Returns the element Ex1: Yes


method from the tuple/list T2=(34,22,56,78,12,90)
having maximum >>large=max(T2)
value. >>large
90
Syntax: max(<tuple>) Ex 2:
TP2=[‘fig’,’apple’,’mango’)
>>max(TP2)
• Take tuple name as mango #based on unicode
argument and returns
a element.
• Can be applied on Ex 3:
sequences(list/tuple) T3=(1,2.4,’a’,(3,4))
only if the sequence >>max(T3) #gives error
contains values of
same type. Otherwise
produces an error
min() • Returns the element Ex1: Yes
method from the tuple/list T2=(34,22,56,78,12,90)
having minimum value. >>small=min(T2)
>>small
Syntax: min(<tuple>) 12
• Take tuple name as Ex 2:
argument and returns TP2=[‘fig’,’apple’,’mango’)
a element. >>min(TP2)
apple #based on unicode
index() • Returns the first index Ex 1: Yes
method of the first matched S=(13,14,15,16,17)
item from the tuple >>S.index[14]
Syntax: 1
tuplename.index(item)
• If the element is not
found then it raises an
value error exception
count() • Returns the count of Ex 1: Yes
method the item passed as N1= (7,2,3,2,2,4,5,2,7)
argument. >>Val = N1.count(7)
• If the item is not >>Val
present in the list, it 2
returns zero. >>N1.count(10)
Syntax: 0
tuplename.count(item)
tuple() • It is a constructor Ex 1: Yes
method method that can be P1= tuple([1,2,3])
used to create tuples >>P1
from different type of (1,2,3)
values. Ex 2:
• Takes a sequence type P2= tuple({1:10,2:20,3:30})
as argument and >>P2
returns a tuple (1,2,3) #takes only the keys
• With no argument it and creates a tuple.
just returns a empty
tuple.
DICTIONARIES
⦁ It is another collection in Python but with different in way of storing and
accessing. Other collection like list, tuple, string are having an index associated
with every element but Python Dictionary have a “key” associated with every
element. That’s why python dictionaries are known as KEY:VALUE pairs.
⦁ Like with English dictionary we search any word for meaning associated
with it, similarly in Python we search for “key” to get its associated value rather
than searching for an index.
Syntax to create dictionary:
dictionary_name = {key1:value,key2:value,….}
Example
>>> emp = {"empno":1,"name":"Shahrukh","fee":1500000}
Here Keys are : “empno”, “name” and “fee”
Values are: 1, “Shahrukh”, 1500000
Note:
⦁ Dictionary elements must be between curly brackets
⦁ Each value must be paired with key element
⦁ Each key-value pair must be separated by comma(,)
Dict1 = {} # empty dictionary
To access Dictionary elements we need the “key”
>>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>> mydict['salary']
>> 25000
If you try to access “key” which is not in the dictionary, python will raise an
error
>>>mydict[‘comm’] #Error

TRAVERSING THROUGH A DICTIONARY


mydict={'Empno':1,'Name':'Shivam','Dept':'sales','Salary':25000}
for key in mydict: #WILL TRAVERSE THROUGH THE KEYS
print(key,'=',mydict[key])
OUTPUT:
'Empno' = 1,
'Name'=Shivam'
'Dept' = 'sales',
'Salary'= 25000
Accessing keys and values simultaneously
>>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.keys()
dict_keys(['empno', 'name', 'dept', 'salary'])
>>>mydict.values()
dict_values([1, 'Shivam', 'sales', 25000])
We can convert the sequence returned by keys() and values() by using list()
as shown below:
>>> list(mydict.keys()) ['empno', 'name', 'dept', 'salary']
>>> list(mydict.values())
[1, 'Shivam', 'sales', 25000]
Keys must be unique
MULTIPLE WAYS OF CREATING A DICTIONARY
⦁ Initializing a Dictionary : in this method all the key:value pairs of
dictionary are written collectively separated by commas and enclosed in curly
braces
Student={“roll”:1,”name”:”Scott”,”Per”:90}
⦁ Adding key:value pair to an empty Dictionary : in this method we first
create empty dictionary and then key:value pair are added to it one pair at a
time
For example
Alphabets={} #Empty dictionary
Or
Alphabets = dict()
⦁ Creating dictionary from name and value pairs: using the dict()
constructor of dictionary, you can also create dictionary initialized from
specified set of keys and values. There are multiple ways to provide keys and
value to dict()
Specific key:value pairs as keyword argument to dict()
Student=dict(roll=1,name=‘scott’,per=89)

Specify comma-separated key:value pairs


student = dict({‘roll’:1,’name’:’scott’,’per’:89})
Specify keys separately and corresponding values separately: in this
method keys and values are enclosed separately in parenthesis and are given
as arguments to the zip() inside dict()
Emp = dict(zip((‘empno’,’name’,’dept’),(1,’Scott’,’HR’)))
You can add new element to dictionary as :
⦁ dictionaryName[“key”] = value

Nesting Dictionaries :
You can add dictionary as value inside a dictionary. This type of
dictionary known as nested dictionary.
For example:
Visitor ={‘Name’:’Scott’,’Address’:{‘hno’:’11A/B’,’City’:’Kanpur’,
’PinCode’:’208004’},‘Name’:’Peter’,’Address’:{‘hno’:’11B/A’,’City’:’Kanpur’,
’ PinCode’:’208004’}
To print elements of nested dictionary is as :
>>> Visitor['Name'] 'Scott'
>>> Visitor['Address']['City'] # to access nested elements 'Kanpur'

UPDATE THE VALUE


Dictionaryname[“key”]=value
>>> data={1:100, 2:200,3:300,4:200}
>>> data[3]=1500
>>> data[3] # 1500
DELETE ELEMNTS/ WHOLE DICTIONARY
del dictionaryName[“Key”]
>>> D1 = {1:10,2:20,3:30,4:40}
>>> del D1[2]
>>> D1 1:10,3:20,4:40
⦁ If you try to remove the item whose key does not exists, the python
runtime error occurs.
⦁ del D1[5] #Error

dictionaryName.pop([“Key”])
>>> D1 = {1:10,2:20,3:30,4:40}
>>> D1.pop(2) 1:10,3:20,4:40
Note: if key passed to pop() doesn’t exists then python will raise an exception.
Pop() function allows us to customized the error message displayed by use of
wrong key
>>> d1
{'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'}
>>>d1.pop(‘a’)
>>> d1.pop(‘d‘,’Not found’) Not found
We can check the existence of key in dictionary using “in” and “not in”.
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>> 'a' in alpha
True
>>>’e’ in alpha False
>>>’e’ not in alpha True
⦁ If you pass “value” of dictionary to search using “in” it will return False
>>>’apple’ in alpha False
To search for a value we have to search in
dict.values()
>>>’apple’ in alpha.values()

PRETTY PRINTING
To print dictionary in more readable form we use json module. i.e. import json
and then call the function dumps()
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>>import json
>>> print(json.dumps(alpha,indent=2))
{
"a": "apple",
"c": "cat",
"b": "boy",
"d": "dog"
}

METHODS/FUNCTIONS IN DICTIONARY

METHOD EXPLANATION EXAMPLE


len() ● Returns the length of >>>alpha = {'a': 'apple', 'b': 'boy', 'c':
dictionary i.e. the count 'cat', 'd': 'dog'}
of elements (key:value >>> len(alpha)
pairs) in dictionary 4

clear() ● Removes all items from >>>alpha.clear()


dictionary and >>>alpha # {}
dictionary becomes
empty dictionary

get() ● This method is used >>>alpha.get(‘b’) # boy


value of given key, if key
>>>alpha.get(‘z’) #Error, nothing
not found it raises an will print
exception >>>alpha.get(‘z’,’not found’)
Not found
items() ● This method returns all >>>alpha = {'a': 'apple', 'b': 'boy', 'c':
the items in the 'cat', 'd': 'dog'}
dictionary s a sequence >>> mytuple = alpha.items()
of (key,value) tuple >>>for item in mytuple:
print(item)
(‘a’,’apple’)
(‘b’,’boy’)
(‘c’,’cat’)
(‘d’,’dog’)
keys() ● Returns all the >>> alpha.keys()
keys in the dict_keys(['a', 'b', 'c', 'd'])
dictionary as a sequence
of keys(not in list form)
values() ● Return all the values in >>> alpha.values()
the dictionary as a dict_values(['apple', 'boy', 'cat', 'dog'])
sequence of keys

update() ●Merges the key:value >>> d1={1:100,2:200,3:300,4:400}


pair from the new >>> d2={1:111,2:222,5:555,4:444}
dictionary into the >>> d1.update(d2)
original dictionary, >>> d1
adding or replacing as {1: 111, 2: 222, 3: 300, 4: 444, 5:
needed. The items in the 555}
new dictionary are >>>d2
added to the old one and {1: 111, 2: 222, 5: 555, 4: 444}
override
Syntax:
d1.update(d2)
fromkeys() ● Returns a new >>d1=dict.fromkeys([1,2,3])
dictionary with the given >>d1
set of elements as the >>{1:None,2:None,3:None}
keys of the dictionary.
● Default value is None d2=dict.fromkeys([1,2,3],100)
● Given value is >>d2
assigned to each key >>{1:100,2:100,3:100}
Syntax:
dict.fromkeys(seq,value)
setdefault() ● Inserts a new key:value >>marks={1:300,2:500,3:800}
pair. >>marks.setdefault(5:900)
● If the given key is not >>900
already present in the >>marks
dictionary,it will add the >>{1:300,2:500,3:800,5:900}
specified new key:value >>marks.setdefault(3:750)
pair to the dictionary >>800
and return the value of >>marks
the added key. >>{1:300,2:500,3:800,5:900}
● If the given key is
already present ,it will
not be updated,but the
current value associated
to the specified key is
returned.
copy() ● Returns a shallow copy >>mark1={1:300,2:500,3:800}
of the dictionary (just a
>>mark2=mark1.copy()
reference) >>mark2
>>{1:300,2:500,3:800}
pop() ● It not only delete the >>emp={‘name’:’sheela’,’age’:23,’sal’:
keyvalue pair but also 20000}
return the >>emp.pop(‘age’)
corresponding value 23
● It also allows you to >>emp
specify what to display >>”{‘name’:’sheela’,’sal’:20000}
when the given key does >>emp.pop(‘dept’, “Not found”)
not exist. >>”Not found”
popitem() ● It will remove >>emp={‘name’:’sheela’,’age’:23,
the last dictionary ’Sal’:20000}
item are return >>emp.popitem()
key,value. >>(‘Sal’,20000)

sorted() ● Sorts and returns the >>D={31:’bcd’,2:’abb’,23:’ccc’}


dictionary by sorting the>>val2=sorted(D)
keys >>[2,23,3]
● By default in ascending >>val3=sorted(D,reverse=True)
>>[31,23,2]
If values should be sorted
>>val2=sorted(D.values())
>>[‘abb’,’bcd’,’ccc’]
min() ● These functions return >>d={1.5:’N’,3.5:’S’,3.2:’A’,2.4:’C’}
max() the highest value,lowest >>min(d)
sum() value and sum of values >>1.5
in dictionary >>max(d)
● This will work only if >>3.5
all the values in >>sum(d)
dictionary is of numeric >>10.6
type

You might also like