0% found this document useful (0 votes)
112 views24 pages

Abu Hamour Branch, Doha - Qatar: M.E.S Indian School (Mesis)

The document discusses strings in Python including defining strings, string operators, string functions and methods. Strings are defined using single, double or triple quotes. They are immutable sequences of characters that can be indexed, sliced and traversed. Basic operators like + and * are used for concatenation and replication. Membership and comparison operators are also covered. Common string methods like capitalize, find, isalpha etc. are explained with examples.
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)
112 views24 pages

Abu Hamour Branch, Doha - Qatar: M.E.S Indian School (Mesis)

The document discusses strings in Python including defining strings, string operators, string functions and methods. Strings are defined using single, double or triple quotes. They are immutable sequences of characters that can be indexed, sliced and traversed. Basic operators like + and * are used for concatenation and replication. Membership and comparison operators are also covered. Common string methods like capitalize, find, isalpha etc. are explained with examples.
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/ 24

M.E.

S INDIAN SCHOOL (MESIS)


ABU HAMOUR BRANCH, DOHA – QATAR
NOTES [2024-2025]
Class & Div. : XII B Subject : Computer Science
Lesson / Topic : 2. Python Revision Tour II Date : 31/03/2024
=====================================================================================================

Ref. No: CS-N-02

String

 String are character enclosed in quotes of any type like single quotation marks, double
quotation marks and triple quotation marks.
Eg : ‘Computer’
“Computer”
‘’’Computer’’’
 String are immutable.
 Empty string has 0 characters.
 String is sequence of characters, each character having unique position or index.
Forward Indexing 0 1 2 3 4 5
p y t h o n
-6 -5 -4 -3 -2 -1 Backward Indexing
Length of String :

str = “python”
l = len(str)
print(“The length of string is “, l)
The length of string is 6

Traversing a String :

 Iterating through an element of String, one character at a time.


 Each character are accessible through unique index.

Eg : str = ‘python’ for ch in str :


for ch in str : print(ch, end = ‘ @ ‘)
print(ch) p@y@t@h@o@n
p
y
t
h
o
n

ACD-105, REV 0, 27.03.2021


String Operators :

 Basic Operators
 Membership Operators
 Comparison Operators
Basic Operators :

 + operator is Concatenation Operator


Eg :
>>>print(‘tea’ + ‘pot’)
teapot
>>>print(‘tea’ + ‘11’)
tea11
>>>print(‘100’ + ‘12’)
10012
 * operator is Replication Operator
Eg :
>>>print(‘tea’ * 3)
teateatea
>>>print(‘100’ * 6)
100100100100100100
>>>print(‘tea’ * ‘pot’)
TypeError

Membership Operators :
 in - returns True if character / substring occurs in a given string, otherwise False.
 Out - returns False if character / substring occurs in a given string, otherwise True.
Eg :
ch = ‘a’
str1 = ‘pan’
str2 = ‘panel’
str3 = ‘japan’
t1 = ch in str1
t2 = str1 in str2
t3 = str1 not in str3
print(t1, t2, t3, sep = ‘ ‘)
True True False
Comparison Operators :

 All relational Operators are comparison operator (<, <=, >, >=, ==, !=).
 In case of characters Uppercase letters are considered smaller than the lowercase letters.
 Python compares two strings through relational operators using character by character
comparison of their Unicode Values.
ACD-105, REV 0, 27.03.2021
Eg :
>>>’comp’ < ‘computer’
True
>>>’comp’ < ‘Computer’
False
>>>’COMPUTER’ > ‘computer’
False
>>>’computer’ > ‘compUter’
True

Ordinal/ Unicode Value :


Characters Ordinal Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Eg :
>>>ord(‘4’) >>>chr(52)
52 ‘4’
>>>ord(‘B’) >>>chr(66)
66 ‘B’
>>>ord(‘d’) >>>chr(100)
100 ‘d’

String Slice :
 String slice is the part of a String containing some contiguous character from the string.
 Eg : ‘or’ , ‘corpor’, ‘tion’, ‘n’ are slice of String ‘corporation’.
0 1 2 3 4 5 6 7 8 9 10
c o r p o r a t i o n
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>>str = ‘corporation’
>>>str[0 : 4]
‘corp’
>>>print(str[3 : 6])
‘por’
>>>print(str[-5 : -2])
‘ati’
>>>print(str[ : -2])
‘corporati’
>>>print(str[2 : ])
‘rporation’
>>>print(str[2 : 8 : 2])
‘roa’
>>>print(str[ : : -2])
‘niaorc’
>>>print(str[ : : 2])
‘croain’
ACD-105, REV 0, 27.03.2021
String Function and Methods :
Python offers many built-in functions for string manipulation.

Function Functionality Example


string.capitalize( ) Returns a copy of the string with its str1 = “python programming”
first character capitalized in a print(str1.capitalize())
sentence. Python programming
string.find Returns the lowest index in the str1.find(“Ice”, 5, 10)
(sub, start, end) string where the substring sub is 7
found within the slice range of str1.find(“tea”, 5, 10)
start and end. -1
Returns -1 if sub is not present.
string.isalnum( ) Returns true if the character in the str1 = “python123”
string are alphanumeric and there str2 = “python”
is at least one character otherwise str3 = “123”
false. str4 = “ “
str1.isalnum()
True
str2.isalnum()
True
str3.alnum()
True
str4.alnum()
False
string.isalpha( ) Returns true if all the characters in str1.isalpha()
the string are alphabet and there is False
at least one character otherwise str2.isalpha
false. True
str3.isalpha()
False
str4.isalpa()
False
string.isdigit( ) Returns true if all the characters in str1.isdigit()
the string are digits and there is at False
least one character otherwise str2.isdigit()
false. False
str3.isdigit()
True
str4.isdigit()
False

ACD-105, REV 0, 27.03.2021


Function Functionality Example
string.islower( ) Returns true if all the cased str5 = “COMPUTER”
characters in the string are str6 = “Computer”
lowercase and there is at least one str7 = “computer”
character otherwise false. str5.islower()
False
str6.islower()
False
str7.islower()
True
str8 = “computer123”
str8.islower()
True
string.isupper( ) Returns true if all the cased str9 = “Computer123”
characters in the string are str9.isupper()
uppercase and there is at least one True
character otherwise false. str10 = “COMPUTER123”
str10.isupper()
True
str5.isupper()
True
str6.isupper()
False
str7.isupper()
False
string.lower( ) Returns a copy of the string str5 = “COMPUTER”
converted to lowercase. str6 = “Computer”
str7 = “computer”
str5.lower()
‘computer’
str6.lower()
‘computer’
Str7.lower()
‘computer’
string.upper( ) Returns a copy of the string str5.upper()
converted to uppercase. ‘COMPUTER’
str6.upper()
‘COMPUTER’
str7.upper()
‘COMPUTER’
string.isspace( ) Returns true if there are only str3 = “123”
whitespaces characters in the str4 = ‘ ‘
string and there is at least one str4.isspace()
character otherwise false. True
str1 = “Python programming”
print(str1.isspace())
False

ACD-105, REV 0, 27.03.2021


Function Functionality Example
string.lstrip([chars] ) Returns a copy of the string with str1 = “Python programming
leading characters removed. language”
If used without any argument, it str1.lstrip(“P”)
removes the leading whitespaces. ‘ython programming language’
str1.lstrip(“Pythons”)
‘ programming language’
str1.lstrip(“Python progs”)
‘amming language’
string.rstrip([chars] ) Returns a copy of the string with str1 = “the great india place”
trailing characters removed. str1.lstrip(“the ground”)
If used without any argument, it ‘the great india plac’
removes the leading whitespaces. str1.lstrip(“the placard”)
‘the great indi’
str1.lstrip(“the card”)
‘the great india pl’

List in Python :

 List is a standard data type of Python that can store a sequence of values belonging to any type.
 List is mutable (modifiable) sequence i.e. element can be changed in place.
Eg :
List = [1, 2, 3, 4, 5]
List1 = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
List2 = ['pan', 'ran', 'oggi', 'blade', 'lemon', 'egg', 'mango']
Creating List :
 List can be created by assigning a variable with the values enclosed in square bracket
separated by comma.
Eg : List = [1, 2, 3, 4, 5]
 Creating Empty List : List with no item is an empty list.
Eg : List = [ ]
It can be created with the function list1 = list(). It generates the empty list with the
name list1. This list is equivalent to 0 and has truth value false.
 Creating List from Existing Sequence :
List1 = list(sequence)
 Eg : List1 = list(‘Computer’)
>>>List1
[’C’, ’o’, ’m’, ’p’, ’u’, ’t’, ’e’, ’r’]
 Creating List from keyboard Input :
list1 = list (input(‘Enter the list item: ’))
or
list1 = eval (input(‘Enter the list item: ’))

ACD-105, REV 0, 27.03.2021


List vs String :

 Similarities :
 Length
 Indexing Slicing
 Membership operators
 Concatenation and Replication operators
 Accessing Individual elements
 Differences :
 Storage : are similar to string, but it stores reference at each index instead of single
characters.
 Mutability : Strings are not mutable, while list are.

Traversing a List :

Syntax :
for <item> in <List> :
Eg :
>>>List1 = [’C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]
>>>for a in List1 :
print(a)
C
o
m
p
u
t
e
r

List Operations :

 Joining Lists : Two Lists can be joined through addition.


Eg :
>>>l1 = [1, 2, 3]
>>>l2 = [4, 5, 6]
>>>l3 = l1 + l2
>>>l3
[1, 2, 3, 4, 5, 6]

 Repeating or Replicating Lists : Multiply (*) operator replicates the list specified number of
times.
Eg :
>>>l1 = [1, 2, 3]
>>>l1 * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

ACD-105, REV 0, 27.03.2021


 Slicing the List : List slices are the subpart of a list extracted out. List slices can be created
through the use of indexes.
Syntax :
Seq = List[start : stop]
creates list slice out of List1 with element falling in between indexes start and stop not
including stop.
Eg :
>>>List1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>>seq = List1[2 : -3]
>>>print(seq)
[3, 4, 5]
 List also supports slice steps.
Syntax :
Seq = List[start : stop : step]
creates list slice out of List with element falling in between indexes start and stop not including
stop, skipping step-1 element in between.
Eg :
>>>List1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>>seq = List1[2 : 7 : 2]
>>>print(seq)
[3, 5, 7]
Using Slices for List Modification :
>>>List = [‘add’, ’sub’, ’mul’]
>>>List [0 : 2] = [‘div, ’mod’]
>>>List [‘div, ’mod’, ’mul’]
>>> List = [‘add’, ’sub’, ’mul’]
>>>List [0 : 2] = ”a”
>>>List [“a”, ”mul”]
>>> List = [1, 2, 3]
>>>List [2 : ] = ”604”
>>>List [1, 2, 3, ’6’, ’0’, ’4’]
>>> List = [1, 2, 3]
>>>List [10 : 20] = ”abcd”
>>>List [1, 2, 3, ’a’, ’b’, ’c’, ’d’]
List Manipulation :
 Appending Elements to a list :
append() method adds a single item to the end of the list.
Syntax :
List.append(item)
Eg :
>>> List = [1, 2, 3]
>>>List.append(6)
>>>print(List)
[1, 2, 3, 6]
ACD-105, REV 0, 27.03.2021
 Updating Element to a list :

Assign new value to the element’s index in list.


Syntax :
List[index] = <new value>
Eg :
>>>List = [1, 2, 3]
>>>List [1] = 4
>>>List [1, 4, 3]

 Deleting Element from a list :

Del statement can be used to remove an individual item, or to remove all items identified
by a slice.
Eg :
>>>List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>del List [5]
>>>print(List)
[1, 2, 3, 4, 5, 7, 8, 9, 10]
>>>List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>del List[5 : 8]
>>>print(List)
[1, 2, 3, 4, 5, 10]
>>>List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>del List
>>>print(List)
[]

Making True copy of a List :


 Assignment does not make a copy of a list.
 Assignment makes two variable to point to same list in memory, called shallow copying.
List1
2 4 5 6
List2

 The changes made in one list will also be reflected to the other list.
 For creating a true copy we need to make
List2 = list (List1)
now List1 and List2 are separate list, called Deep Copy.

ACD-105, REV 0, 27.03.2021


List Functions and Methods :

 The index() Method :


This function returns the index of first matched item from the list.
Syntax : List.index(<item>)
Eg :
>>>list = [12, 14, 15, 17, 14, 18]
>>>list.index(14)
1
If item is not in the list it raises exception value error.

 The append() Method :


This function adds an item to the end of the list.
Syntax : List.append(<item>)
Eg :
>>>list = [12, 14, 15, 17]
>>>list.append(18)
>>>list [12, 14, 15, 17, 18]

 The extend() Method :


This function adds multiple item to the end of the list.
Syntax : List.extend(<item>)
Eg :
>>>list1 = [12, 14, 15, 17]
>>>list2 = [18, 19, 20]
>>>list1.extend(list2)
>>>list1 [12, 14, 15, 17, 18, 19, 20]

 The insert() Method :


This function inserts item at the given position in the list.
Syntax : List.insert (<pos>, <item>)
Eg :
>>>list1 = [12, 14, 15, 17]
>>>list1.insert(2, 200)
>>>list1 [12, 14, 200, 15, 17]

 The pop() Method :


This removes the item at the given position in the list.
Eg :
List1.pop() removes last item in the list
List1.pop(3) removes item at index 3 in the list

ACD-105, REV 0, 27.03.2021


 The remove() Method :
This function removes first occurrence of given item from the list.
Syntax : List.remove(<item>)
Eg :
>>>list1 = [12, 14, 15, 17]
>>>list1.remove(15)
>>>list1 [12, 14, 17]

 The clear() Method :


This function removes all the items from the list.
Syntax : List.clear()
Eg :
>>>list1 = [12, 14, 15, 17]
>>>list1.clear()
>>>list1
[]

 The count() Method :


This function returns the count of the item passed as argument. If given item is not in
the list it returns zero.
Eg :
>>>list1 = [12, 14, 15, 14, 17]
>>>list1.count(14)
2
>>>list1 = [12, 14, 15, 14, 17]
>>>list1.count(18)
0

 The reverse() Method :


This function reverses the item of the list. This is done “in place”, i.e it does not create
new list.
Syntax : List.reverse()
Eg :
>>>list1 = [12, 14, 15, 14, 17]
>>>list1.reverse()
[17, 14, 15, 14, 12]

 The sort() Method :


This function sorts the items of the list, by default in increasing order. This is done “in
place”,i.eit does not create new list.
Syntax : List.sort()
Eg :
>>>list1 = [12, 14, 15, 14, 17]
>>>list1.sort()
[12, 14, 14, 15, 17]
It sorts the string in lexicographic manner. If we want to sort the list in decreasing order, we
need to
>>>list1.sort(reverse = True)

ACD-105, REV 0, 27.03.2021


Tuples in Python :

 Tuple is a standard data type of Python that can store a sequence of values belonging to any
type.
 Tuples are depicted through parenthesis i.e. round brackets.
 Tuples are immutable sequence i.e. element cannot be changed in place.
Eg :
>>>Tup1 = (1, 2, 3, 4, 5)
>>>Tup2 = ('p', 'r', 'o', 'b', 'l', 'e', 'm‘)
>>>Tup3 = ('pan', 'ran', 'oggi', 'blade', 'lemon', 'egg', 'mango‘)

Creating Tuples :

 Tuples can be created by assigning a variable with the values enclosed in round bracket
separated by comma.
Eg :
>>>tup1 = (1, 2, 3, 4, 5)
 Tuples can be created in different ways :
 Empty Tuple :
Tuple with no item is an empty tuple. It can be created with the function T = tuple( ).
It generates the empty tuple with the name T. This list is equivalent to 0 or ‘ ’.
 Single Element Tuple :
Tuple with one item.
Eg : T1 = (9, ) or T1 = 9,
comma is required because Python treats T1 = (9) as value not as tuple element.
 Creating Tuple from Existing Sequence :
Syntax : T1 = tuple(<sequence>)
Eg : T1 = tuple(‘Computer’)
>>>T1
(’C’, ’o’, ’m’, ’p’, ’u’, ’t’, ’e’, ’r’)
 Creating Tuple from Keyboard Input :
Eg :
t1 = tuple(input”Enter tuple element : “))
print(t1)
Enter tuple element : 123456789
(‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’)
tuple = eval(input(“Enter tuple element : “))
print(tuple)
Enter tuple element : (2, 5, ‘yup’, ‘1’, 9)
(2, 5, ‘yup’, ‘1’, 9)

ACD-105, REV 0, 27.03.2021


Tuples vs List :

 Similarities :
 Length
 Indexing Slicing
 Membership operators
 Concatenation and Replication operators
 Accessing Individual elements

 Differences :
 Mutability : Tuples are not mutable, while list are.

Tuple Operations :

 Joining Tuples :
Two tuples can be joined through addition.
Eg :
>>>t1 = (1, 2, 3)
>>>t2 = (4, 5, 6)
>>>t3 = t1 + t2
>>>t3
(1, 2, 3, 4, 5, 6)

 Repeating or Replicating Tuples :


Multiply (*) operator replicates the tuple specified number of times.
Eg :
>>>t1 = (1, 2, 3)
>>>t1 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

 Slicing the Tuples :


Tuple slices are the subpart of a tuple extracted out. Tuple slices can be created through
the use of indexes.
Eg :
Seq = Tuple[start : stop]
creates tuple slice out of t1 with element falling in between indexes start and stop not
including stop.
>>>t1 = (1, 2, 3, 4, 5, 6, 7, 8)
>>>seq = t1[2 : -3]
>>>print(seq)
(3, 4, 5)
tuples also supports slice steps.
Eg : Seq = Tuple[start : stop : step]
creates tuple slice out of tuple with element falling in between indexes start and stop not
including stop, skipping step-1 element in between.
>>>t1 = (1, 2, 3, 4, 5, 6, 7, 8)
>>>seq = t1[2 : 7 : 2]
>>>print(seq)
(3, 5, 7)
ACD-105, REV 0, 27.03.2021
Unpacking Tuples :

Forming a tuple from individual values is called packing and creating individual values from a
tuple’s elements is called unpacking.
Eg :
t = (10, 20, ‘ok’, ‘p’)
x, y, z, w = t
print(t)
print(x, “ : ”, y, “ : ”, z, “ : ”, w)
(10, 20, ‘ok’, ‘p’)
10 : 20 : ok : p

Deleting Tuples :

 We cannot delete individual item of a tuple.


 del statement deletes the complete tuple.

Tuple Functions and Methods :

 The len( ) Method :


This function returns the length of the tuple, i.e. the count of elements in the tuple.
Syntax :
len(<tuple>)
Eg :
>>>t = (10, 20, ‘ok’, ‘P’)
>>>t
(10, 20, ‘ok’, ‘P’)
>>>len(t)
4
 The max( ) Method :
This function returns the element from the tuple having maximum value.
Syntax :
max(<tuple>)
Eg :
>>>t1 = (12, 14, 15, 17, 14, 18)
>>>max(t1)
18
>>>t2 = (“rahim”, “zara”, “anusha”)
>>>max(t2)
‘zara’

 The min( ) Method :


This function returns the element from the tuple having minimum value.
Syntax :
min(<tuple>)
ACD-105, REV 0, 27.03.2021
Eg :
>>>t1 = (12, 14, 15, 17, 14, 18)
>>>min(t1)
12
>>>t2 = (“ram”, “zara”, “anusha”)
>>>min(t2)
‘anusha’

 The index( ) Method :


This function returns the index of first matched item from the tuple.
Syntax :
Tuple.index(<item>)
Eg :
>>>t1 = (12, 14, 15, 17, 14, 18)
>>>t1.index(15)
2
>>>t1.index(9)
ValueError
If item is not in the list it raises exception value.

 The count( ) Method :


This function returns the count of the item passed as argument. If given item is not in
the tuple it returns zero.
Syntax :
tuple.count(<item>)
Eg :
>>>t1 = (12, 14, 17, 14, 18)
>>>t1.count(14)
2
>>>t1.count(22)
0

 The tuple( ) Method :


This function creates tuples from different types of values.
Syntax :
tuple(<sequence>)
Eg :
>>>#creating tuple from string
>>>t = tuple(“abc”)
>>>t
(‘a’, ‘b’, ‘c’)
>>>#creating tuple from list
>>>t1 = tuple([1, 2, 3])
>>>t1
(1, 2, 3)

ACD-105, REV 0, 27.03.2021


#creating tuple from keys of a dictionary
>>>t2 = tuple({1 : “1”, 2 : “2”})
>>>t2
(1, 2)
#creating empty tuple
>>>t = tuple()
>>>t
()
>>>t = tuple(1)
TypeError
tuple( ) can receive argument of sequence type only, like string or list or dictionary.
Any other type of value will lead to an error.

Dictionary - Key : Value Pairs :

Dictionaries are mutable, unordered collections with elements in the form of a key : value
pair that associate keys to value.
 Dictionary are collection or bunch of values in a single variable.
 These are collection of key - value pairs.
 It associates key to values.

Creating a Dictionary :

 Dictionary can be created by including the key : value pair in curly braces.
 Syntax :
<dictionary name> = {<key> : <value>, < key> : <value>, ………}
 Eg : dictionary by the name teachers that stores name of teachers as key and subjects
being taught by them as value of respective key
teachers = {"Lovely" : "Computer Science", "Suman" : "Geography", "Rupam" : "Maths",
"Babli" : "Pol Science"}
 Keys of dictionary must be of immutable type.
key : value pair key value
“Lovely” : ”Computer Science” Lovely Computer Science
”Suman” : “Geography” Suman Geography
”Rupam” : ”Maths” Rupam Maths
”Babli” : ”Pol Science” Babli Pol Science

Accessing elements of a Dictionary :

 Dictionary is accessed through its key.


 Syntax : <dictionary name>[<key>]

ACD-105, REV 0, 27.03.2021


 Eg :
>>>teachers = {“Lovely” : “Computer Science”, “Suman ”: “Geography”, “Rupam” :
“Maths”, “Babli” : “Pol Science”}
>>>teachers [“Rupam”]
‘Maths’
>>>teachers = {“Lovely” : “Computer Science”, “Suman” : “Geography”, “Rupam” :
“Maths”, “Babli” : “Pol Science”}
>>>print(“Rupam teaches : “, teachers [“Rupam”])
Rupam teaches : Maths
 Mentioning dictionary name without any square bracket displays the entire content of the
dictionary.
 Eg :
>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’
‘Babli’ : ‘Pol Science’}

Characteristics of a Dictionary :

 Unordered Set : order that the keys are added doesn't necessarily reflect what order they may
be reported back.
 Not a Sequence
 Indexed by Keys, Not Numbers
 Keys must be Unique : More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment,
the last assignment wins.
 Mutable : which means they can be changed.
 Internally Stored as Mapping : is a mapping of unique keys to values.

John Smith 01

02
Lisa Smith
03
Sam Doe 04
05
Sandra Doe
14
15
Traversing a Dictionary :

 Traversing means accessing each element of a collection.


 For loop helps to traverse each elements of dictionary.

ACD-105, REV 0, 27.03.2021


Syntax :
for <item> in <dictionary> :
process each item here
Eg :
for key in teachers :
print(key, “ : “, teachers[key])
Lovely : Computer Science
Suman : Geography
Rupam : Maths
Babli : Pol Science
 Dictionaries are un-ordered set of elements, the printed order of elements is not same as the
order you stored the elements in.

Accessing Keys or Values Simultaneously :

 To see all keys in dictionary we write <dictionary>.keys( )


Eg :
>>>teachers.key()
dict_keys([‘Lovely’, ‘Suman’, ‘Rupam’, ‘Babli’])
 To see all values in dictionary we write <dictionary>.values( )
Eg :
>>>teachers.values()
dict_values([‘Computer Science’, ‘Geography’, ‘Maths’, ‘Pol Science’])
 We can convert the sequence returned by keys( ) and values( ) function by using list( ).
Eg :
>>>List(teachers.keys())
[‘Lovely’, ‘Suman’, ‘Rupam’, ‘Babli’]
>>>list(teachers.values())
[‘Computer Science’, ‘Geography’, ‘Maths’, ‘Pol Science’]

Adding Element to Dictionary :


Eg :
>>>released[“iphone”] = 2007
>>>released[“iphone 3G”] = 2008
>>>released
[‘iphone’: 2007, ‘iphone 3G’ : 2008]
>>>released = {“iphone”: 2007, “iphone 3G” : 2008, “iphone 3GS”: 2009,
“iphone 4” : 2010, “iphone 4S”: 2011, “iphone 5” : 2012}

ACD-105, REV 0, 27.03.2021


>>>released
{‘iphone’: 2007,
‘iphone 3G’ : 2008,
‘iphone 3GS’: 2009,
‘iphone 4’ : 2010,
‘iphone 4S’: 2011,
‘iphone 5’ : 2012}
>>>released[“iphone 5S”] = 2014
>>>released
{‘iphone’: 2007,
‘iphone 3G’ : 2008,
‘iphone 3GS’: 2009,
‘iphone 4’ : 2010,
‘iphone 4S’: 2011,
‘iphone 5’ : 2012
‘iphone 5S’ : 2014}

Updating Existing Element in a Dictionary :

 Change the value of an existing key using assignment.


 Syntax :
<dictionary name>[<key>] = <value>
 Make sure key must exist in the dictionary otherwise new entry will be added to the dictionary.
 Eg :
>>>released[“iphone 5S”] = 2015
>>>released
{‘iphone’: 2007,
‘iphone 3G’ : 2008,
‘iphone 3GS’: 2009,
‘iphone 4’ : 2010,
‘iphone 4S’: 2011,
‘iphone 5’ : 2012
‘iphone 5S’ : 2015}

Deleting Element From a Dictionary :

 There are two methods for deleting element from a dictionary


 del command : To delete a dictionary element or a dictionary entry, i.e key : value pair
we will use del command.
Eg :
>>>teachers = {“Lovely” : “Computer Science”, “Suman” : “Geography”,
“Rupam” : “Maths”, “Babli” : “Pol Science”}

ACD-105, REV 0, 27.03.2021


>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’}
>>>del teachers[‘Suman’]
>>>print(teachers)
{‘Lovely’ : ‘Computer Science’, ‘Suman’ : ‘Geography’, ‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’}

 pop( ) method : This method will not only delete the key : value pair for mentioned key
but also return the corresponding value.
Syntax :
<dictionary>.pop(<key>)
Eg :
>>>teachers.pop(‘Babli’)
‘Pol Science’
>>>print(teachers)
{‘Lovely’ : ‘Computer Science’, ‘Suman’ : ‘Geography’, ‘Rupam’ : ‘Maths’}
o If we try to delete a key which does not exist, python gives KeyError.
Eg :
>>>del teachers[‘Priya’]
KeyError
o pop( ) method allows you to specify what to display when the given key does not
exist, rather than the default error message.
Syntax :
<dictionary>.pop(<key>,<in case of error show me>)
Eg :
>>>print(teachers)
{‘Lovely’ : ‘Computer Science’, ‘Suman’ : ‘Geography’, ‘Rupam’ : ‘Maths’}
>>>teachers.pop(’Babli’, ‘Teacher not exist’)
‘Teacher not exist’

Checking of Existence of a Key :

 Membership operators in and not in checks the presence of key in a dictionary. It does not
check the presence of value.
Syntax :
<key> in <dictionary>
returns true if given key is present in the dictionary, otherwise false.
<key> not in <dictionary>
returns true if given key is not present in the dictionary, otherwise false.

ACD-105, REV 0, 27.03.2021


Eg :
>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’}
>>>”Lovely” in teachers
True
>>>”Lovely” not in teachers
False

Checking of Existence of a Value :

Eg :
>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’}
>>>”Maths” in teachers.value()
True

Dictionary Functions and Methods :

 The len() Method : This function returns the length of the dictionary.
Syntax :
len(<dictionary>)
Eg :
>>>teachers = {“Lovely” : “Computer Science”, “Suman” : “Geography”,
“Rupam” : “Maths”, “Babli” : “Pol Science”}
>>>len(teachers)
4
 The clear() Method : This function removes all the items from the dictionary.
Syntax :
<dictionary>.clear( )
Eg :
>>>teachers = {“Lovely” : “Computer Science”, “Suman” : “Geography”,
“Rupam” : “Maths”, “Babli” : “Pol Science”}
>>>teachers.clear()
>>>teachers
{}

 The get( ) Method : This function returns the corresponding value for the key.
Syntax :
<dictionary>.get(key,[default])
ACD-105, REV 0, 27.03.2021
Eg :
>>>teachers.get(“Suman”)
‘Geography’
>>>teachers.get(“Suhani”, “not present”)
not present

 The item( ) Method : This function returns all of the item in the dictionary as a sequence of
key : value pair.
Syntax :
<dictionary>.items( )
Eg :
>>>teachers.items()
dict_items = ([(‘Lovely’, ‘Computer Science’), (‘Suman’, ‘Geography’),
(‘Rupam’, ‘Maths’), (‘Babli’, ‘Pol Science’)])

 The key( ) Method : This function returns all of the keys in the dictionary.
Syntax :
<dictionary>.keys( )
Eg :
>>>teachers.keys()
dict_keys = ([‘Lovely’, ‘Suman’, ‘Rupam’, ‘Babli’])

 The values( ) Method : This function returns all the values from the dictionary as a sequence.
Syntax :
<dictionary>.values( )
Eg :
>>>teachers.values()
dict_values = ([‘Computer Science’, ‘Geography’, ‘Maths’, ‘Pol Science’])

 The update( ) Method : This function merges key: value pairs from the new dictionary into the
original dictionary , adding or replacing as needed.
Syntax :
<dictionary>.update(<new dictionary>)
Eg :
>>>new_teachers = {“Jyothi” : “Computer Science”, “Suman” : “Geography”,
“Sima” : “history”}
>>>teachers.update(new_teachers)
>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’
‘Jyothi’ : ‘Computer Science’,
‘Sima’ : ‘History’}

ACD-105, REV 0, 27.03.2021


Sorting Techniques :

 Bubble Sort :

 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Eg :
First Pass :
(5 1 4 2 8)  (1 5 4 2 8), Here algorithm compares the first two elements, and swaps
since 5 > 1.
(1 5 4 2 8)  (1 4 5 2 8), swap since 5 > 4.
(1 4 5 2 8)  (1 4 2 5 8), swap since 5 > 2.
(1 4 2 5 8)  (1 4 2 5 8), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.

Second Pass :
(1 4 2 5 8)  (1 4 2 5 8)
(1 4 2 5 8)  (1 2 4 5 8), swap since 4 > 2.
(1 2 4 5 8)  (1 2 4 5 8)
(1 2 4 5 8)  (1 2 4 5 8),
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.

Coding :
void bubble_sort(int A[ ], int n)
{
int temp;
for(int k = 0; k< n-1; k++)
{
# (n-k-1) is for ignoring comparisons of elements which have already been compared in
earlier iterations
for(int i = 0; i < n-k-1; i++)
{
if(A[ i ] > A[ i+1])
{
// here swapping of positions is being done.
temp = A[ i ];
A[ i ] = A[ i+1 ];
A[ i + 1] = temp;
}
}
}
}

ACD-105, REV 0, 27.03.2021


Insertion Sort :

 Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our
hands.
Eg :

Coding :
void insertion_sort (int A[ ] , int n)
{
for(int i = 0 ; i < n ; i++)
{
/*storing current element whose left side is checked for its correct position.*/
int temp = A[ i ];
int j = i;
/* check whether the adjacent element in left side is greater or less than the current
element. */
while (j > 0 && temp < A[ j -1])
{
// moving the left side element to one position forward.
A[ j ] = A[ j-1];
j= j - 1;
}
// moving current element to its correct position.
A[ j ] = temp;
}
}

*********

ACD-105, REV 0, 27.03.2021

You might also like