St.
John’s Public School
Unit 1: Python Revision Tour - II
03/08/2024 1
Strings in Python
Strings in Python
Item not supported in Python
Traversing a String
String Operators – Concatenation, Replication, Membership & Comparison
ord() and chr() method in String
ord() – takes single character and returns ASCII value.
chr() – takes ASCII value and returns the character.
String Slicing in Python
String Slicing in Python
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
S1 M e s h N e t w o r k i n g
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String Methods in Python
S.no. Function Description Example
1 len() Returns number of characters in the given s1="Java Beans"
string. print(s1)
Java Beans
2 count() Returns No. of occurrences of a substring in the s4="Table in Cabin"
given string. print(s4.count("ab"))
2
3 capitalize() Returns the copy of the string with the first s3="email id"
character capitalized. print(s3.capitalize())
Email id
4 title() Returns the string with first letter of each word s3="email id"
is upper case. print(s3.title())
Email Id
5 find() Returns the lowest index of the given string. s2="Database Table"
print(s2.find("ab"))
3
print(s2.find("ab",6))
10
String Methods in Python
S.no. Function Description Example
6 isalnum() Returns True if all the characters in the string s5="Room245"
are alphabets or numbers, otherwise False. print(s5.isalnum())
True
7 isalpha() Returns True if all the characters in the string s6="Hotel"
are alphabets, otherwise False. print(s6.isalpha())
True
8 isdigit() Returns True if all the characters in the string s7="2500"
are numbers, otherwise False. print(s7.isdigit())
True
9 isspace() Returns True if all the characters in the string s8=" "
are white space, otherwise False. s9=""
print(s8.isspace())
True
print(s9.isspace())
False
10 islower() Returns True if all the characters in the string str2="technique"
are upper case alphabets, otherwise False. print(str2.islower())
True
String Methods in Python
S.no. Function Description Example
11 isupper() Returns True if all the characters in the string str3="GRAPHICS"
are lower case alphabets, otherwise False. print(str3.isupper())
True
12 istitle() Returns True if first character of each word is str4="Exam Result"
in sentence case, otherwise False. str5="Science exhibition"
print(str4.istitle())
True
print(str5.istitle())
False
13 lower() Returns a copy of the string converted to str6="SCHOOL"
lower case. print(str6.lower())
school
14 upper() Returns a copy of the string converted to str7="election"
upper case. print(str7.upper())
ELECTION
15 swapcase() Returns a copy of the string with uppercase str8="MatPlotLib"
characters converted to lowercase and vice print(str8.swapcase())
versa. mATpLOTlIB
String Methods in Python
S.no. Function Description Example
16 startwith() Returns True if string starts with a given topic="Textile Industry"
prefix, otherwise False. print(topic.startswith("Tex"))
True
17 endswith() Returns True if string ends with a given suffix, topic="Textile Industry“
otherwise False. print(topic.endswith("Try"))
False
18 partition() Splits the string at the first occurrence of sentence="Rooftop Solar Power"
argument and returns a 3-tuple containing print(sentence.partition("Solar"))
the part before separator, separator itself and ('Rooftop ', 'Solar', ' Power')
the part of separator. print(sentence.partition("Top"))
('Rooftop Solar Power', '', '')
19 lstrip() Returns a copy of the string with leading print(text.lstrip("newR"))
characters removed. able Energy Sources
print(text.lstrip("newr"))
Renewable Energy Sources
20 rstrip() Returns a copy of the string with trailing text="Confidential Data"
characters removed. print(text.rstrip("at"))
Confidential D
Lists in Python
Lists
It is a sequence data type in Python in which elements are separated by commas.
List elements are enclosed within a pair of Square brackets [ and ].
Lists are mutable which means we can change the elements of a list in place.
Types of Lists:
Empty List: It has no elements. Eg: L = [ ]
List of Integers: It consists of Integers. Eg: L1 = [5, 8, 10, 15]
List of Numbers: It consists of both integers and Floating point Nos. Eg: L2 = [2.3,1.2,3.8]
List of Characters: It consists of a sequence of characters. Eg: L3 = [‘L’,’ e’, ’m’, ’o’, ’n’]
List of Strings: It consists of a collection of strings. Eg: Fruits= [“Apple”, ”Banana”, “Grapes”]
List of Mixed data types: It consists of mix of different data values.
Eg: Student = [15, “John”, “XI F”, ‘M’, 78.5 ]
Single Element List
A list with single element can be created in the following way.
Method : L=[10]
Creating a List
A list can be created by using the following ways:
L=list(sequence)
Empty list : List1 = [] or List1=list()
From String : L1=list('Practical') [‘P’, ’r’, ’a’, ’c’, ’t’, ’i’, ’c’, ’a’, ’l’]
From Tuple : Tup1 = ('x','y','z‘) List2=list(Tup1) [‘x’, ‘y’, ‘z’]
Using input : L3=list(input("Enter List Elements? "))
It creates a list of character elements.
Using eval : L4=list(eval(input('Enter List elements? ')))
It creates a list of numerical elements.
Lists vs Strings
Lists are mutable whereas Strings are immutable.
L1 = [10,15,20,30,50]
L1[2] = 25 #It is valid and element @ index 2 will be modified to 25.
print(L1)
Output:
[10,15,25,30,50]
Name = “MASS”
Name[1] = ‘E’ #It is invalid because string is immutable.
Output:
TypeError: ‘str' object does not support item assignment
Similarities with Strings & Tuples
Strings, Tuples and Lists are similar in operations.
len() – It counts the no. of elements in list.
Indexing – Forward & Backward Indexing in list.
Slicing – It is used to extract a part from a list.
Use of Membership Operators – in and not in
Concatenation & Replication - + and *
Accessing List elements
List elements are accessed using indexes.
While accessing list elements, if we pass a negative index, Python adds the
length of the list to the index to get the forward index.
If Length=10 L[-6] = L[-6+10]=L[4]
List Operations
Traversing a List:
Traversing just means to process every element in a list, usually from left end
to right end.
Python allows for 2 ways to do this:
Method 1: if all you need is the value of each element in the list
MyList = list(eval(input(“Enter a list of elements? “)))
for val in MyList:
print(val)
Method 2: The other way uses the location / index of the elements in the list.
for k in range(len(MyList)):
print(MyList[k])
List Operations
1)Joining Lists.
2)Repeating or Replicating Lists.
3)Slicing the Lists.
4)Comparing Lists: < <= > >= == !=
List Operations
1) Joining Lists: List1+List2 (Both operands must be of List types)
List1=[10,20,30]
List2=[40,50]
Tup1=(200,300)
List1 + List2 – Output => [10,20,30,40,50]
List1 + Tup1 - TypeError: can only concatenate list (not "tuple") to list
List1+100 - TypeError: can only concatenate list (not "int") to list.
2) Repeating or Replicating tuples: List1*4
Output => [10,20,30, 10,20,30, 10,20,30, 10,20,30]
List Operations
3) Slicing the List: Sub parts of List will be extracted.
List1[2:5] List1[3:25] List2[-6:4]
seq=List_Object[start:stop:step]
L1[0:8:3] - include every 3rd element.
L2[::4] - included every 4th element.
We can use + and * operators with List slices.
L1=(5,10,15,20,25,30,35,40)
L1[2:5]*3 [15,20,25,15,20,25,15,20,25]
L1[1:4]+[50,60,75] [10,15,20,50,75,100]
4) Comparing Lists: < <= > >= == !=
It compares the corresponding first elements of two lists and returns
True / False according to the value.
Note: while comparison int and float values are considered equal.
List1=[15,25,5,10,20]
List2=[50,35,40,35,30]
List1>List2
False Because 15 > 50 False
List1<List2
True Because 15 < 50 True
4) Comparing Lists: < <= > >= == !=
If first elements are matched in both the list, then it will check the
corresponding second values of the lists and so on.,
Note: while comparison int and float values are considered equal.
MyList1=[100,50,30,200,80]
MyList2=[100,40,75,250,150]
MyList1>MyList2
True
Here first set of values are 100 and 100 (Both first elements are equal)
So it checks next set of values 50 and 40, 50 > 40, so it returns True.
List Manipulations
List operations: appending, updating, deleting, etc.,
L1 = [3,8,12,20]
L1.append(25) #Add 25 at the end of the list
print(L1) Output: [3, 5, 8, 12, 20, 25]
L1[2] = 10 #update the element at index 2 with value 10
print(L1) Output: [3, 5, 10, 12, 20, 25]
del L1[3] #delete the element at index position 3.
print(L1) Output: [3, 5, 10, 20, 25]
del L1[1:3] #delete the element from index 1 to index 3
print(L1) Output: [3, 25]
Shallow Copy in List
Deep Copy in List – using list()
Deep Copy in List – using copy()
Tuples in Python
Tuples
It is a sequence data type in Python in which elements are separated by commas.
Tuple elements are enclosed within a pair of parenthesis ( and ).
Tuples are Immutable which means we cannot change the elements of a tuple in place.
Types of Tuples:
Empty Tuple: It has no elements. Eg: T = ( )
Tuple of Integers: It consists of Integers. Eg: T1 = (5, 8, 10, 15)
Tuple of Numbers: It consists of both integers and Floating point Nos. Eg: T2 = (2.3,1.2,3.8)
Tuple of Characters: It consists of a sequence of characters. Eg: T3 = (‘L’,’ e’, ’m’, ’o’, ’n’)
Tuple of Strings: It consists of a collection of strings. Eg: Fruits= (“Apple”, ”Banana”, “Grapes”)
Tuple of Mixed data types: It consists of mix of different data values.
Eg: Student = (15, “John”, “XI F”, ‘M’, 78.5 )
Single Element Tuple
A tuple with single element can be created in the following ways.
Method 1 : t=10,
Method 2: t=(10,)
Note: If the statement is t=(10), then Python considers it as an integer value
10 only, Not a tuple with 10.
Creating tuple
A tuple can be created by using the following ways:
T=tuple(sequence)
Empty tuple : tup1 = () or tup1=tuple()
From String : t1=tuple('Practical') (‘P’, ’r’, ’a’, ’c’, ’t’, ’i’, ’c’, ’a’, ’l’)
From List : L = ['x','y','z'] t2=tuple(L) (‘x’, ‘y’, ‘z’)
Using input : t3=tuple(input("Enter Tuple Elements? "))
It creates a tuple of character elements.
Using eval : t4=tuple(eval(input('Enter Tuple Values? ')))
It creates a tuple of numerical elements.
Accessing Tuples
Tuple elements are accessed using indexes like Lists.
While accessing tuple elements, if we pass a negative index, Python adds
the length of the tuple to the index to get the forward index.
If Length=10 T[-3] = T[-3+10]=T[7]
Lists vs Tuples
Lists are mutable whereas Tuples are immutable.
L1 = [10,15,20,30,50]
L1[2] = 25 #It is valid and element @ index 2 will be modified to 25.
print(L1)
Output:
[10,15,25,30,50]
Tup1 = (10,15,20,30,50)
Tup1[2] = 25#It is invalid because tuple is immutable.
Output:
TypeError: 'tuple' object does not support item assignment
Traversing a Tuple:
Traversing just means to process every element in a tuple, usually from left end
to right end.
Python allows for 2 ways to do this:
Method 1: if all you need is the value of each element in the tuple
Tup1 = tuple(eval(input(“Enter tuple of elements? “)))
for x in Tup1:
print(x)
Method 2: The other way uses the location / index of the elements in the tuple
for k in range(len(Tup1)):
print(Tup1[k])
Similarities with Lists
Tuples and Lists are similar in operations.
len() – It counts the no. of elements in tuple.
Indexing – Forward & Backward Indexing
Slicing – It is used to extract a part from a tuple.
Use of Membership Operators – in and not in
Concatenation & Replication - + and *
Tuple Operations
1)Joining Tuples.
2)Repeating or Replicating tuples.
3)Slicing the Tuples.
4)Comparing Tuples: < <= > >= == !=
5)Packing and Unpacking Tuples:.
6)Deleting tuples.
Tuple Operations
1) Joining Tuples: T1+T2
(Both operands must be of tuple types)
tuple + string, tuple + list - Error.
t1+(100) - Error. Because (100) is not tuple with 100. It is an
integer 100.
2) Repeating or Replicating tuples: t1*5
Tuple Operations
3) Slicing the Tuples: Sub parts of Tuples will be extracted.
t1[2:5] t1[3:25] t2[-6:4]
seq=T[start:stop:step]
t1[0:8:2] - include every 2nd element.
t2[::5] - included every 5th element.
We can use + and * operators with tuple slices.
T=(5,10,15,20,25,30,35,40)
T[3:6]*2 (20,25,30,20,25,30)
T[2:4]+(50,75,100) (15,20,50,75,100)
4) Comparing Tuples: < <= > >= == !=
It compares the corresponding first elements of two tuples and returns
True / False according to the value.
Note: while comparison int and float values are considered equal.
T1=(15,25,5,10,20)
T2=(50,35,40,35,30)
T1>T2
False Because 15 > 50 False
T1<T2
True Because 15 < 50 True
4) Comparing Tuples: < <= > >= == !=
If first elements are matched in both the tuple, then it will check the
corresponding second values of the tuples and so on.,
Note: while comparison int and float values are considered equal.
T1=(100,50,30,200,80)
T2=(100,40,75,250,150)
T1>T2
True
Here first set of values are 100 and 100 (Both first elements are equal)
So it checks next set of values 50 and 40, 50 > 40, so it returns True.
5) Packing and Unpacking Tuples:
Forming a tuple from individual values is called Packing.
Creating individuals values from a tuple's elements is called Unpacking.
Note: No. of variables in the left side of assignment must match the no. elements in the
tuple.
Colour=('Blue', 'Green', 'Orange', 'Yellow') # Packing
print(Colour)
Output:
('Blue', 'Green', 'Orange', 'Yellow')
House1, House2, House3, House4 = Colour # Unpacking
print(House1, House2, House3, House4)
Output:
Blue Green Orange Yellow
6) Deleting tuples:
It is not possible to delete an individual element. But it is
possible to delete a complete tuple.
del T[3] - Error
del T - Legal
Tuple Functions and Methods:
1. len(tuple) - returns length (No. of elements) of a tuple.
2. max() - returns the element from the tuple having maximum value.
3. min() - returns the element from the tuple having minimum value.
Note: all values should be of same type.
4. sum() – returns the sum of all the elements of a tuple.
Example:
Tuple Functions and Methods:
5. index() - returns the index of first occurrence of the given element in a
tuple.
6. count() - returns the no. of occurrences of the given element in a tuple.
7. tuple() - constructor method that can be used to create tuples from
different types of values.
Dictionaries in Python
Dictionaries
Dictionaries: These are mutable unordered collections with elements in the form of a key :
value pairs that associate keys to values.
List and Strings: index associated with each data item.
Dictionaries: collection of key-value pairs.
Curly brackets are used to mark the beginning and the end of the dictionary. { }
Dictionaries are arranged on the basis of keys.
Dictionaries are also called associative arrays or mappings or hashes.
Notes: Keys of a dictionary must be of immutable types. String or Number or Tuple.
Creating Dictionary:
D={}
D1={"Sunday" : 1, "Monday" : 2, ....., "Saturday" : 7}
Accessing Elements of a Dictionary
Dictionaries: These are mutable unordered collections with elements in the form of a key :
value pairs that associate keys to values.
A dictionary operation that takes a key and finds the corresponding value is called lookup.
D1["Wednesday"] gives 4
Vowel={"V1" : "a", "V2" : "e", "V3" : "i", "V4" : "o", "V5" : "u"}
Vowel["V4"] = ‘O‘
print(Vowel)
Vowel["V10"] = Key Error.
Note: In Python dictionaries, the elements (key : value pairs) are unordered. One cannot
access elements as per specific order.
Traversing a Dictionary
Syntax:
for <item> in <Dictionary> :
process item here.
Eg:
Student = {"Name": "Sam", "Class" : "12 D", "Marks" : 75}
for key in Student:
print(key, " : ", Student[key])
Home Work:
Create an Employee dictionary with Names as keys and Salaries as Values
with at least 4 employee records.
Home Work: Employee Dictionary Creation:
EmpDict = {"Guna":37500, "Malvika" : 64500, "John" : 48000, “Sneha" : 25000}
for EName in EmpDict:
print(EName, " # ", EmpDict[EName])
Note: Dictionaries are unordered set of elements, the printed order of
elements is not same as the order you stored the elements in.
Using keys(), values() & items() methods
Accessing Keys or Values Simultaneously:
d.keys() d.values() d.items()
Example:
Product={"TV":28000, "Oven":8500, "AC":45000, "Mobile":17500}
print(Product.keys())
dict_keys(['TV', 'Oven', 'AC', 'Mobile'])
print(Product.values())
dict_values([28000, 8500, 45000, 17500])
print(Product.items())
dict_items([('TV', 28000), ('Oven', 8500), ('AC', 45000), ('Mobile', 17500)])
Converting Dictionary elements to lists.
Converting sequence returned by keys() and values() functions by using list().
list(d.keys()) list(d.values()) - It converts to a list of keys or list of values.
Example:
Product={"TV":28000, "Oven":8500, "AC":45000, "Mobile":17500}
print(list(Product.keys()))
['TV', 'Oven', 'AC', 'Mobile']
print(list(Product.values()))
[28000, 8500, 45000, 17500]
Characteristics of Dictionaries
Dictionary is an unordered set of key:value pairs.
Dictionary is not a sequence.
Dictionaries are Indexed by keys not Numbers.
Keys must be unique. Two keys can have same values.
Dictionaries are mutable.
Dictionaries are internally stored as Mappings.
Working with Dictionaries
1. Initializing a Dictionary:
Book={“Java":40, “SQL":25, “Python":80, “C++":75, “VB":15 }
2. Empty Dictionary:
Method 1: Student={}
Method 2 (Using constructor) : Student = dict()
Note: using dict() method to create a dictionary takes longer time compared to
traditional method of enclosing values in { }. It should be avoided until it becomes a
necessity.
Working with Dictionaries
3. Creating a Dictionary from name and value pairs:
Method 1: Specific key:value pairs as keyword arguments to dict() function.
Student=dict(name:'Jai', mark:80) - Python automatically convert argument into
string.
>>>Student
{'name' : 'Jai', 'mark' : 80}
Method 2: Specific comma-separated key:value pairs.
Student=dict({'name' : 'Jai', 'mark' : 80})
Method 3: Specific keys and corresponding values separately using zip() function.
Student=dict(zip(('name','mark'),('Jai',80)))
Method 4: Specify key : value pairs in form of sequences.
Student=dict( [ ['name','Jai'], ['mark',80] ] )
Adding / Updating Elements in Dictionaries
Adding Elements to Dictionary:
It is possible to add new elements (key:value) pair using assignment operator. But
the key being added must not exist in dictionary and must be unique.
Student['city'] = 'Jaipur'
Updating Existing elements in a Dictionary:
{'name' : 'Jai', 'mark' : 80}
Student['mark']=85
Nesting Dictionary: Dictionary within another Dictionary.
Stud = {'Karthik' : {'age' : 16, 'avg' : 92.5}, 'Joash' : {'age' : 17, 'avg' : 85.2}}
Stud['Joash']['avg']
Output
85.2
Deleting Elements in Dictionaries
Method 1: using del command
del <dictionary> [ <key>]
icc={'India':'Rohit','Pakistan':'Babar','Australia':'Cummins','Eng':'Buttler'}
del icc['Pakistan']
print(icc)
{'India': 'Rohit', 'Australia': 'Cummins', 'Eng': 'Buttler'}
Note: Deleting non existent key raised to Key Error.
Deleting Elements in Dictionaries
Method 2: using pop() method - It not only delete the key : value pair but also
return the corresponding value.
<dictionary>.pop(<key>)
pop() - allows to specify what to display when the given key does not exist rather
than the default error message.
icc.pop('Srilanka','Not found')
'Not found‘
icc.pop('Australia','Not found')
'Cummins'
print(icc )
{'India': 'Rohit', 'Eng': 'Buttler'}
Traversing in Dictionaries
Method 1: Default method (Using keys()):
for key in D1:
print(key, “ : “, value)
Method 2: using items() method:
for key, value in D1.items():
print(key, “ : “, value)
Use of Membership Operators in Dictionaries
Checking the existence of a key.
in and not in operator check the membership only in keys of the dictionary and not in
values.
<key> in <dictionary>
<key> not in <dictionary>
Example:
>>>d1={ 1:10, 2:20, 3:30, 4:40, 5:50, 6:60, 7:70, 8:80 }
>>> print(4 in d1)
True
>>> print(60 in d1)
False
>>> print(‘Six’ not in d1)
True
>>> print(2 not in d1)
Pretty printing of a Dictionary
To print dictionary in a way that makes it more readable and presentable by importing json
(Java Script Object Notation – Syntax for storing and exchanging data) module and dumps()
method (convert python object to JSON string).
Syntax: json.dumps(<Dictionary Name>, indent=<n>) and n is a number of spaces in front of
key:value pair.
Example:
import json
TV = { 'Ikon' : 22000 , 'Samsung' : 29300, 'LG' : 27800, 'Sony' : 38000, 'Philips' : 24000 }
print(json.dumps(TV,indent=10))
{
"Ikon": 22000,
"Samsung": 29300,
"LG": 27800,
"Sony": 38000,
"Philips": 24000
}
Dictionary Functions and Methods
Product={'Butter':60,'Rice':80,'Wheat':65,'Sugar':40,'Milk':50,'Bread':30}
len() - returns the length of the dictionary.
print(len(Product)) Output: 6
get() - get the item with the given key.
Product.get('Sugar') Output: 40
items() - returns all the items in the dictionary as a sequence.
ITEMS=Product.items()
for x in ITEMS:
print(x)
('Butter', 60)
('Rice', 80)
('Wheat', 65)
('Sugar', 40)
('Milk', 50)
('Bread', 30)
Dictionary Functions and Methods
Product={'Butter':60,'Rice':80,'Wheat':65,'Sugar':40,'Milk':50,'Bread':30}
keys() - returns all the keys in the dictionary.
print(Product.keys())
dict_keys(['Butter', 'Rice', 'Wheat', 'Sugar', 'Milk', 'Bread'])
values() - returns all the values in the dictionary.
print(Product.values())
dict_values([60, 80, 65, 40, 50, 30])
clear() - removes all items from the dictionary. But del statement will remove the dictionary
itself.
Product.clear()
print(Product)
{}
Dictionary Functions and Methods
update() - merges key:value pairs from the new dictionary into the original dictionary
adding or replacing as needed.
The items in the new dictionary are added to the old one and override any items already
there with the same keys.
>>>print(Books)
{'Java': 500, 'Python': 350, 'Oracle': 800}
>>>print(NewBooks)
{'Networks': 250, 'Python': 375, 'Multimedia': 180}
>>>Books.update(NewBooks)
>>>print(Books)
{'Java': 500, 'Python': 375, 'Oracle': 800, 'Networks': 250, 'Multimedia': 180}
Dictionary Functions and Methods
popitem() – removes the last item from the dictionary.
Football = { "brand": “Nivia Storm”, “company": “Flipkart", “price": 299 }
Football.popitem()
{ “brand” : “Nivia Storm”, “company” : “Flipkart” }
fromkeys() – returns a dictionary with the specified keys and the specified value.
Degree = (‘MBA', ‘MCA', ‘MCom')
Fees = 30000
Course = dict.fromkeys(Degree, Fees)
print(Course)
Course = {‘MBA‘:30000, ‘MCA‘:30000, ‘MCom‘:30000}
Dictionary Functions and Methods
setdefault()– returns the value of the item with the specified key.
Football = { "brand": “Nivia Storm”, “company": “Flipkart", “price": 299 }
x = Football.setdefault(“company", “Amazon")
print(x)
Flipkart
Note : If the key does not exist, it will insert new key:value pair.
Football = { "brand": “Nivia Storm”, “company": “Flipkart", “price": 299 }
x = Football.setdefault(“year", 2022)
print(x)
print(Football)
2022
{ "brand": “Nivia Storm”, “company": “Flipkart", “price": 299, “year”: 2022 }
2/28/2024 67