Abu Hamour Branch, Doha - Qatar: M.E.S Indian School (Mesis)
Abu Hamour Branch, Doha - Qatar: M.E.S Indian School (Mesis)
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 :
Basic Operators
Membership Operators
Comparison Operators
Basic Operators :
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
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.
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: ’))
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 :
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]
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)
[]
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.
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)
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)
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 :
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
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 :
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’
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.
Eg :
>>>teachers
{‘Lovely’ : ‘Computer Science’,
‘Suman’ : ‘Geography’,
‘Rupam’ : ‘Maths’,
‘Babli’ : ‘Pol Science’}
>>>”Maths” in teachers.value()
True
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’}
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;
}
}
}
}
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;
}
}
*********