PYTHON Revision PPT Part 2
PYTHON Revision PPT Part 2
String
• String are character enclosed in quotes of any type like single
quotation marks, single quotation marks and triple quotation marks.
– ‘Computer’
– “Computer”
– ‘’’Computer’’’
• String are immutable
• Empty string has 0 characters.
• String is sequence of characters, each character having unique
position or index
0 1 2 3 4 5
Forward Indexing
p y t h o n
-6 -5 -4 -3 -2 -1 Backward Indexing
Length of String
c o r p o r a t i o n
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
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
first character capitalized in a
sentence.
C
o
m
p
u
t
e
r
List Operations
• Joining Lists: Two Lists can be joined through addition.
>>>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
>>>l1=[1,2,3] >>>l1*3 [1,2,3,1,2,3,1,2,3]
• Slicing the List: List slices are the subpart of a list extracted out.List slices can be created through the
use of indexes.
Seq=List[start:stop] : creates list slice out of List1 with element falling in between indexes
start and stop not including stop.
>>>List1=[1,2,3,4,5,6,7,8] >>>seq=List1[2,-3] >>>seq [3,4,5]
List also supports slice steps. Example, 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.
>>>List1=[1,2,3,4,5,6,7,8] >>>seq=List1[2,7,2] >>>seq [3,5,7]
Using Slices for List Modification
>>> List=*‘add’,’sub’,’mul’+ >>>List*0:2+=*‘div,’mod’+ >>>List
*‘div,’mod’,’mul’+
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
List Functions and Methods
• The index() Method: This function returns the index of first matched item from the list.
List.index(<item>)
>>>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.
List.append(<item>)
>>>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.
List.extend(<item>)
>>>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.
List.insert(<pos>,<item>)
>>>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.
List1.pop() removes last item in the list
List1.pop(3) removes item at index 3 in the list
• The remove() Method: This function removes first occurrence of given item from the list.
List.remove(<item>)
>>>list1=[12,14,15,17] >>>list1.remove(15) >>>list1 [12,14,17]
• The clear() Method: This function removes all the items from the list.
List.clear()
>>>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.
>>>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.
List.reverse()
>>>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.e it does not create new list.
List.sort()
>>>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)
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.
• Example
– 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.
– Example: tup1=(1,2,3,4,5)
• Tuples can be created in different ways:
– Empty Tuple: Tuple with no item is a 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.
T1=(9,) or T1=9, comma is required because Python treats T1=(9) as value not as
tuple element.
– Creating Tuple from Existing Sequence:
T1=tuple(<sequence>)
Example: T1=tuple(‘Computer’)
>>>T1
(’C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Creating Tuple from Keyboard Input:
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.
>>>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
>>>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.
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] >>>seq (3,4,5)
tuples also supports slice steps. Example, 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] >>>seq (3,5,7)
Unpacking Tuples
Forming a tuple from individual values is called packing
and creating individual values from a tuple’s elements
is called unpacking.
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. len(<tuple>)
• The max( ) Method: This function returns the element from the tuple having maximum value
. max(<tuple>)
• The min( ) Method: This function returns the element from the tuple having minimum value
. min(<tuple>)
• The index( ) Method: This function returns the index of first matched item from the
tuple. Tuple.index(<item>)
Mentioning dictionary name without any square bracket displays the entire content of
the dictionary.
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
Traversing a Dictionary
• Traversing means accessing each element of a collection.
• For loop helps to traverse each elements of dictionary as per following
syntax: for <item> in <dictionary>:
process each item here
• Dictionaries are un-ordered set of elements, the printed order of elements is not same
as the order you stored the elements in.
Exercise: WAP to create phone dictionary of all your friends and print it.
Accessing Keys or Values Simultaneously
If we try to delete a key which does not exist, python gives KeyError.
pop( ) method allows you to specify what to display when the
given key does not exist, rather than the default error
message, with the following syntax:
<dictionary>.pop(<key>,<in case of error show me>)
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.
Checking of Existence of a Value
Dictionary Functions and Methods
• The len() Method: This function returns the length of the
dictionary. len(<dictionary>)
• The clear() Method: This function removes all the items from the
dictionary. <dictionary>.clear( )
• The item( ) Method: This function returns all of the item in the dictionary as a sequence
of key:value pair.
<dictionary>.items( )
• The key( ) Method: This function returns all of the keys in the
dictionary. <dictionary>.keys( )
• The values( ) Method: This function returns all the values from the dictionary as a
sequence. <dictionary>.values( )
• The update( ) Method: This function merges key: value pairs from the new dictionary into
the original dictionary , adding or replacing as needed.
• <dictionary>.update(<new dictionary>)
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.
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