Advanced Python Programming (UNIT-1) | 4321602
Unit-I: Basic of Python data structure - Dictionary, Tuple and Set (Marks-18)
The basic python structure in python include list, set, tuple, and dictionary.
Introduction to Strings
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes.
Python treats single quotes the same as double quotes. Creating strings is as simple as
assigning a value to a variable.
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
Syntax:
str = "Hi Python !"
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
Example:
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 1
Advanced Python Programming (UNIT-1) | 4321602
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
O/P:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Explain String built-in functions in python. SUMMER-2023
Strings Methods and Built-in Functions:
Python provides various in-built functions that are used for string handling. Those are
Method Purpose Example
len() Returns length of the given string. Example:
str1="Python
Language"
print(len(str1))
O/P:
15
lower() Returns all characters of given string in Example:
lowercase str=”PyTHOn”
print(str.lower())
O/P:
python
upper() Returns all characters of given string in Example:
uppercase str=”PyTHOn”
print(str.upper())
O/P:
PYTHON
replace() Replaces the old sequence of characters Example:
with the new sequence. If the optional str = "Java is Object-
argument count is given, only the first Oriented and Java is
count occurrences are replaced. Portable "
Syntax: str2=
str.replace(old, new[, count]) str.replace("Java","Pyth
old : An old string which will be replaced. on")
new : New string which will replace the old print(str2)
string. str3 =
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 2
Advanced Python Programming (UNIT-1) | 4321602
count : The number of times to process the str.replace("Java","Pyth
replace. on",1)
print(str3)
O/P:
Python is Object-
Oriented and Python is
Portable
Python is Object-
Oriented and Java is
Portable
find() Finds substring in the whole string and Example:
returns index of the first match. It returns - str1 = "python is a
1 if substring does not match programming language"
Syntax: str2 = str1.find("is")
str.find(sub[, start[,end]]) str3 = str1.find("java")
sub :it specifies sub string. print(str2,str3)
start :It specifies start index of range. O/P:
end : It specifies end index of range. 7 -1
index() index() method is same as the find() Example:
method except it returns error on failure. str1 = "python is a
This method returns index of first occurred programming language"
substring and an error if there is no match str2 = str1.index("is")
found print(str2)
Syntax: str3 = str1.index("p",5)
index(sub[, start[,end]]) print(str3)
sub :it specifies sub string. str5 = str1.index("java")
start :It specifies start index of range. print(str5)
end : It specifies end index of range. O/P:
7 12 Substring not
found
isalnum() Checks whether the all characters of the Example:
string is alphanumeric or not. A character str1 = "python"
which is either a letter or a number is str2 = "python123"
known as alphanumeric. It does not allow str3 = "python@123"
special chars even spaces. print(str1. isalnum())
print(str2. isalnum())
print(str3. isalnum())
O/P:
True True False
isdigit() Rreturns True if all the characters in the Example:
string are digits. It returns False if no str1 = "12345"
character is digit in the string str2 = "python123"
print(str1.isdigit())
print(str2.isdigit())
O/P:
True False
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 3
Advanced Python Programming (UNIT-1) | 4321602
islower() Returns True if all characters in the string Example:
are in lowercase. It returns False if not in str1 = "python"
lowercase. str2="PytHOn"
print(str1.islower())
print(str2.islower())
O/P:
True False
isupper() Rreturns True if all characters in the string Example:
are in uppercase. It returns False if not in str1 = "PYTHON"
uppercase. str2="PytHOn
O/P:
True False
capitalize() Returns a string where the first character is Example:
upper case, and the rest is lower case. str1 = "python is FUN!"
x = str1.capitalize()
print (x)
O/P:
Python is fun!
title() Converts the first character of each word to Example:
upper case str1 = "Welcome to my
world"
x = str1.title()
print(x)
O/P:
Welcome To My World
swapcase() Swaps cases, lower case becomes upper Example:
case and vice versa str1 = "Hello My Name
Is PETER"
x = str1.swapcase()
print(x)
O/P:
hELLO mY nAME iS
peter
strip() Remove spaces at the beginning and at the Example:
end of the string str1 = " python "
x = str1.strip()
print(x)
O/P:
pythonyho
lstrip() Remove spaces to the left of the string Example:
str1 = " banana "
x = str1.lstrip()
print("of all fruits", x,
"is my favorite")
O/P:
of all fruits banana is
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 4
Advanced Python Programming (UNIT-1) | 4321602
my favorite
rstrip() Remove any white spaces at the end of the Example:
string: str1 = " banana "
x = str1.rstrip()
print("of all fruits", x,
"is my favorite")
O/P:
of all fruits banana is
my favorite
count() Returns the number of times a specified Example:
value occurs in a string str1 = "I love apples,
apple are my favorite
fruit"
x = str1.count("apple")
print(x)
O/P: 2
join() Converts the elements of an iterable into a Example:
string myTuple = ("John",
"Peter", "Vicky")
x = "#".join(myTuple)
print(x)
O/P:
John#Peter#Vicky
split() Splits the string at the specified separator, Example:
and returns a list str1 = "welcome to the
python"
x = str1.split()
print(x)
O/P:
['welcome', 'to', 'the',
'python']
isprintable() Returns True if all characters in the string Example:
are printable str1 = "Hello! Are you
#1?"
x = str1.isprintable()
print(x)
O/P: true
What is List? What are the use of List in python and write characteristics of List.
SUMMER-2023
Introduction to List
In Python, the sequence of various data types is stored in a list. A list is a collection of
different kinds of values or items. The comma (,) and the square brackets [enclose the
List's items] serve as separators.
Lists are used to store multiple items in a single variable.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 5
Advanced Python Programming (UNIT-1) | 4321602
Elements of the List need not be of same type.It means List can represents
homogeneous(same) as well as heterogeneous(different) elements.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Characteristics of a Python List
Ordered: Lists maintain the order in which the data is inserted.
Mutable: In list element(s) are changeable. It means that we can modify the items stored
within the list.
Heterogeneous: Lists can store elements of various data types.
Dynamic: List can expand or shrink automatically to accommodate the items accordingly.
Duplicate Elements: Lists allow us to store duplicate data. Lists are created using square
brackets:
List Operations
Various operations that can be performed on list are:
Creating a list
Access individual Element of the List.
Traversing in a List
Searching a List
List Concatation
List Repetition
Creating a list
To create a list in Python, we use square brackets ([]). Here's what a list looks like:
ListName = [ListItem, ListItem1, ListItem2, ListItem3, ...]
# Creating an empty List
empty_List = []
# Creating a List of Integers
integer_List = [26, 12, 97, 8]
# Creating a List of floating point numbers
float_List = [5.8, 12.0, 9.7, 10.8]
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 6
Advanced Python Programming (UNIT-1) | 4321602
# Creating a List of Strings
string_List = ["Monday", "Tuesday", "Wednesday"]
# Creating a List containing items of different data types
List = [1, "Monday", 9.5, 'D']
# Creating a List containing duplicate items
duplicate_List = [1, 2, 1, 1, 3,3, 5, 8, 8]
The list() constructor returns a list in Python.
List_1 =list( (1, "Monday", 9.5, 'D'))
print(List_1)
Accessing Values/Elements in List in Python
Elements stored in the lists are associated with a unique integer number known as an
index. The first element is indexed as 0, and the second is 1, and so on. So, a list
containing six elements will have an index from 0 to 5.
For accessing the elements in the List, the index is mentioned within the index operator
([ ]) preceded by the list's name.
Another way we can access elements/values from the list in python is using a negative
index. The negative index starts at -1 for the last element, -2 for the last second element,
and so on.
Example:
My_List = [3, 4, 6, 10, 8]
print(My_List[2])
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 7
Advanced Python Programming (UNIT-1) | 4321602
print(My_List[4])
print(My_List[-1])
print(My_List[-5])
O/P: 6 8 8 3
Access Range of Elements in List
we can access the elements stored in a range of indexes using the slicing operator (:).
The index put on the left side of the slicing operator is inclusive, and that mentioned
on the right side is excluded.
Slice itself means part of something. So when we want to access elements stored at
some part or range in a list we use slicing
Example:
my_List = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
# Accessing elements from index beginning to 5th index
print(my_List[:6])
# Accessing elements from index 3 to 6
print(my_List[3:7])
# Accessing elements from index 5 to end
print(my_List[5:])
# Accessing elements from beginning to end
print(my_List[:])
# Accessing elements from beginning to 4th index
print(my_List[:-6])
# Accessing elements from index -8th to -6th index
print(my_List[-8:-5])
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 8
Advanced Python Programming (UNIT-1) | 4321602
O/P:
['a', 'b', 'c', 'd', 'e', 'f']
['d', 'e', 'f', 'g']
['f', 'g', 'h', 'i', 'j']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['a', 'b', 'c', 'd']
['c', 'd', 'e']
Traversing in a List
Traversing a list means access each elements of list.
Using while loop:
Example:
list1 = [3, 5, 7, 2, 4]
count = 0
while (count < len(list1)):
print (list1 [count])
count = count + 1
O/P: 3 5 7 2 4
Using for loop:
Example:
list1 = [3, 5, 7, 2, 4]
for i in list1:
print (i)
O/P: 3 5 7 2 4
Using for and range:
Example:
list1 = [3, 5, 7, 2, 4]
length = len (list1)
for i in range (0, len (list1)):
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 9
Advanced Python Programming (UNIT-1) | 4321602
print (list1 [i])
O/P: 3 5 7 2 4
Searching a List
You can search elements in a list using Membership operator
Membership Check of an element in a list: We can check whether a specific element is
a part/ member of a list or not.
Example:
my_List = [1, 2, 3, 4, 5, 6]
print(3 in my_List)
print(10 in my_List)
print(10 not in my_List)
O/P: True False True
List Concatation
One list may be concatenated with itself or another list using ‘+’ operator.
Example:
List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
concat_List = List1 + List2
print(concat_List)
O/P: [1, 2, 3, 4, 5, 6, 7, 8]
List Repetition
We can use the ‘*’ operator to repeat the list elements as many times as we want.
Example:
my_List = [1, 2, 3, 4]
print(my_List*2)
O/P: [1, 2, 3, 4, 1, 2, 3, 4]
List built in methods of list and give their use. WINTER – 2021
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 10
Advanced Python Programming (UNIT-1) | 4321602
Differentiate remove( ) and pop( ) methods of list with suitable example. SUMMER-
2022
List Methods and Built-in Functions
Method Purpose Example
append() Adds an element at the end of the list Example:
fruits = ["apple", "banana",
"cherry"]
fruits.append("orange")
print(fruits)
O/P:['apple', 'banana', 'cherry',
'orange']
insert() Adds an element at the specified position Example:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
O/P: ['apple', 'orange', 'banana',
'cherry']
extend() Add the elements of a list (or any iterable), Example:
to the end of the current list fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
O/P: ['apple', 'banana', 'cherry',
'Ford', 'BMW', 'Volvo']
clear() Removes all the elements from the list Example:
fruits = ["apple", "banana",
"cherry"]
fruits.clear()
print(fruits)
O/P: []
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 11
Advanced Python Programming (UNIT-1) | 4321602
remove() Removes the item with the specified value Example:
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
O/P: ['apple', 'cherry'][ae', ']
pop() Removes the element at the specified Example:
position.If you do not specify position fruits = ['apple', 'banana', 'cherry']
than it will remove the element from list fruits.pop(1)
which is added last. fruits.pop()
print(fruits)
print(fruits)
O/P: ['apple', 'cherry']
['apple', 'banana']
count() Returns the number of elements with the Example:
specified value fruits = ["apple", "banana",
"cherry"]
x = fruits.count("xyz")
print(x)
fruits = ["apple", "banana",
"cherry","banana"]
x = fruits.count("banana")
print(x)
O/P: 0 2
sort() Sort the list alphabetically Example:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
O/P: ['BMW', 'Ford', 'Volvo']
reverse() Reverses the order of the list Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 12
Advanced Python Programming (UNIT-1) | 4321602
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
O/P:['cherry', 'banana', 'apple']
index() Returns the index of the first element with Example:
the specified value fruits = ['apple', 'banana',
'cherry','cherry']
x = fruits.index("cherry")
print(x)
O/P:2
min() Returns the smallest of the values or the Example:
smallest item in an list list1 = [10, 20, 4, 45, 99]
print(min(list1))
O/P: 4
max() Returns the largest of the values or the Example:
largest item in an list list1 = [10, 20, 4, 45, 99]
print(max(list1))
O/P: 99
sum() Returns sum of all elements of the list Example:
List1=[1,2,3,4,5]
Print(sum(list1))
O/P:15
Define Set and how is it created in python? SUMMER-2022
Introduction to Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Characteristics of set
Python’s built-in set type has the following characteristics:
Sets are unordered.
Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the set must be of
an immutable type.
Creating a set
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 13
Advanced Python Programming (UNIT-1) | 4321602
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}.
Python also provides the set() method, which can be used to create the set by the passed
sequence.
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"}
print(Days)
print(type(Days))
O/P:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
Example: (using set() method)
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"])
print(Days)
print(type(Days))
O/P:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
Accessing Values in Sets
We cannot access individual value from the list. We can access all the elements together as
shown blow:
Example:
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"])
print("looping through the set elements ... ")
for i in Days:
print(i)
O/P:
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Adding items to the set
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 14
Advanced Python Programming (UNIT-1) | 4321602
Python provides the add() method method which can be used to add some particular item to
the set. The add() method is used to add a single element
Example:
color = {“red”, ”green”. ”blue”}
print("\nprinting the original set ... ")
print(color)
print("\nAdding other colors to the set...");
color.add(“yellow”)
color.add(“white”)
print("\nPrinting the modified set...");
print(color)
O/P:
printing the original set ...
{‘red’, ’blue’, ’green’}
Adding other colors to the set...
{‘red’, ’blue’, ’yellow’, ’green’}
Write how to add, remove, an element from a set .Explain why POP is different form
remove. SUMMER-2023
Removing items from the set
Python provides the discard() method and remove() method which can be used to remove the
items from the set.
The difference between these function, using discard() function if the item does not exist in
the set then the set remain unchanged whereas remove() method will through an error.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
O/P:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 15
Advanced Python Programming (UNIT-1) | 4321602
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
O/P:
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}
We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element will
be popped from set.
Example-3 Using pop() function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
O/P:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 16
Advanced Python Programming (UNIT-1) | 4321602
printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
{'May', 'April', 'February', 'March'}
Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task, There is
one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the Python will
not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the Python will raise an error.
What is set? Write a python program to perform several set operations such as union,
intersection and difference. WINTER-2022
Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference, and
symmetric difference.
Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.
1. Union of two Sets
To combine two or more sets into one set in Python, use the union() function. All of the
distinctive characteristics from each combined set are present in the final set.
Example 1: using union | operator
E = {0, 2, 4, 6, 8}
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 17
Advanced Python Programming (UNIT-1) | 4321602
N = {1, 2, 3, 4, 5}
print(E | N) #printing the union of the sets
O/P:
{0, 1, 2, 3, 4, 5, 6, 8}
Python also provides the union() method which can also be used to calculate the union of
two sets. Consider the following example.
Example 2: using union() method
E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print(E.union(N)) #printing the union of the sets
O/P:
{0, 1, 2, 3, 4, 5, 6, 8}
The intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection()
function. The intersection of the two sets is given as the set of the elements that common in
both sets.
Example 1: Using & operator
E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print(E & N) #prints the intersection of the two sets
O/P:
{2, 4}
Example 2: Using intersection() method
E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print(E.intersection(N)) #prints the intersection of the two sets
O/P:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 18
Advanced Python Programming (UNIT-1) | 4321602
{2, 4}
Example 3:
set1 = {1, 2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
O/P:
{1, 2, 5}
The intersection_update() method
The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it
modifies the original set by removing the unwanted items, on the other hand, the
intersection() method returns a new set.
Example:
a = {‘red’,’green’,’blue’}
b = {‘yellow’,’blue’,’black’}
c = {‘blue’,’white’,’pink’}
print(a.intersection_update(b, c))
print(a)
O/P:
None
{'blue'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or
intersection() method. Suppose there are two sets A and B, and the difference is A-B that
denotes the resulting set will be obtained that element of A, which is not present in the set B.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 19
Advanced Python Programming (UNIT-1) | 4321602
Example 1 : Using subtraction ( - ) operator
E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print(E - N)
O/P:
{0,8,6}
Example 2 : Using difference() operator
E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print(E.difference(N))
O/P:
{0,8,6}
Symmetric Difference of two sets
The Symmetric Difference of two sets can be computed using Python's
symmetric_difference() method. This method returns a new set containing all the
elements in either but not in both. Consider the following example:
Example - 1: Using ^ operator
a = {1,2,3,4,5,6}
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 20
Advanced Python Programming (UNIT-1) | 4321602
b = {1,2,9,8,10}
c = a^b
print(c)
O/P:
{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
O/P:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows us to use the comparison operators like,
==: checks if two sets have the same elements, regardless of their order.
!=: checks if two sets are not equal.
<: checks if the left set is a proper subset of the right set (i.e., all elements in the left
set are also in the right set, but the right set has additional elements).
<=: checks if the left set is a subset of the right set (i.e., all elements in the left set are
also in the right set).
>: checks if the left set is a proper superset of the right set (i.e., all elements in the
right set are also in the left set, but the left set has additional elements).
>=: checks if the left set is a superset of the right set (i.e., all elements in the right set
are also in the left).
Example:
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 21
Advanced Python Programming (UNIT-1) | 4321602
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
O/P:
True
False
False
Python Built-in set methods
SN Method Description
1 add(item) It adds an item to the set. It has no effect if
the item is already present in the set.
2 clear() It deletes all the items from the set.
3 copy() It returns a shallow copy of the set.
4 difference_update(....) It modifies this set by removing all the items
that are also present in the specified sets.
5 discard(item) It removes the specified item from the set.
6 intersection() It returns a new set that contains only the
common elements of both the sets. (all the
sets if more than two are specified).
7 intersection_update(....) It removes the items from the original set that
are not present in both the sets (all the sets if
more than one are specified).
8 Isdisjoint(....) Return True if two sets have a null
intersection.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 22
Advanced Python Programming (UNIT-1) | 4321602
9 Issubset(....) Report whether another set contains this set.
10 Issuperset(....) Report whether this set contains another set.
11 pop() Remove and return an arbitrary set element
that is the last element of the set. Raises
KeyError if the set is empty.
12 remove(item) Remove an element from a set; it must be a
member. If the element is not a member,
raise a KeyError.
13 symmetric_difference(....) Remove an element from a set; it must be a
member. If the element is not a member,
raise a KeyError.
14 symmetric_difference_update(....) Update a set with the symmetric difference of
itself and another.
15 union(....) Return the union of sets as a new set.
(i.e. all elements that are in either set.)
16 update() Update a set with the union of itself and
others.
Define Tuple and how is it created in python? SUMMER-2023
What is a tuple? What does it mean that a tuple is immutable? WINTER-2022
Tuples
A tuple is a built-in data structure in python that is an ordered collection of object. Unlike
lists, tuples come with limited functionality.
Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.
Creating a tuple
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 23
Advanced Python Programming (UNIT-1) | 4321602
A tuple can be written as the collection of elements separated by a comma, enclosed in
parenthesis (). Although parentheses are not required, but it is good practice to use.
A tuple can be define as follow:
Example:
tup1 = ("Rohan", "Physics", 21, 69.75)
tup2 = (1, 2, 3, 4, 5)
tup3 = ("a", "b", "c", "d")
tup4 = (25.50, True, -55, 1+2j)
print(type(tup1))
print(type(tup2))
O/P:
<class ‘tuple’>
<class ‘tuple’>
An empty tuple can be created as follow:
Tup=( )
Note that even if there is only one object in a tuple, you must give a comma after it.
Otherwise, it is treated as a string.
Example:
tup=(“hello”)
tup1=(“hello” , )
print(type(tup))
print(type(tup1))
O/P:
<class ‘string’>
<class ‘tuple’>
Example:
tup=(10,20,30,40,50)
print(tup)
count=0
for i in tup:
print(“tup[%d] = %d”%(count,i))
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 24
Advanced Python Programming (UNIT-1) | 4321602
count+=1
O/P:
(10, 20, 30, 40, 50)
tup[0] = 10
tup[1] = 20
tup[2] = 30
tup[3] = 40
tup[4] = 50
Write a python program for indexing and slicing in tuple. WINTER-2022
Tuple Indexing and Slicing
The Tuple Indexing and Slicing in the tuple is similar to list. The indices of a tuple start with
0 and goes to length(tuple)-1.
The items in the tuple can be accessed by using the index [] operator.
Each element of the tuple can be accessed or manipulated by using the index number.
They are two types of indexing −
Positive Indexing
Negative Indexing
Positive Indexing
In positive the first element of the tuple is at an index of 0 and the following elements are at
+1 and as follows.
In the below figure, we can see how an element in the tuple is associated with its index or
position.
Example 1
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple[3])
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 25
Advanced Python Programming (UNIT-1) | 4321602
print(tuple[7])
O/P:
7
4
Negative Indexing
In negative indexing, the indexing of elements starts from the end of the tuple.
That is the last element of the tuple is said to be at a position at -1 and the previous
element at -2 and goes on till the first element.
In the below figure, we can see how an element is associated with its index or position of a
tuple.
Example 1
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple[-2])
print(tuple[-8])
O/P:
4
2
Slicing tuples
The slice operator allows you to specify where to begin slicing, where to stop slicing, and
what step to take. Tuple slicing creates a new tuple from an old one.
Example 1
print(tup[0:3])
print(tup[0:3:2])
print(tup[7:3:-1])
print(tup[-1:-5:-1])
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 26
Advanced Python Programming (UNIT-1) | 4321602
O/P:
(5, 2, 9)
(5, 9)
(4, 1, 8, 5)
(3, 4, 1, 8)
Remove Tuple Items
You cannot remove items in a tuple like list using del keyword.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely.
Example 1
tuple= (5,2,9,7,5,8,1,4,3)
del tuple[2] # error- can’t delete single item from tuple
del tuple
print(tuple)
O/P:
NameError: name 'tuple1' is not defined.
Tuple Operations
In Python, Tuple is a sequence. Hence, we can concatenate two tuples with + operator and
concatenate multiple copies of a tuple with "*" operator. The membership operators "in" and
"not in" work with tuple object.
Let’s take tuple t1=(1, 2, 3,4, 5) and t2=( 6, 7, 8, 9)
Operator Description Example
It concatenates the tuple mentioned on
Concatenation t1+t2=(1,2,3,4,5,6,7,8,9)
either side of the operator
The repetition operator enables the tuple
Repetition t2*2= (6,7,8,9,6,7,8,9)
elements to be repeated multiple times.
It returns true if a particular item is Print(2 in t1)
Membership
exists in the tuple otherwise false O/P: True
Length It is used to get the length of the tuple len(t1)= 5
Built-In Functions
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 27
Advanced Python Programming (UNIT-1) | 4321602
Let’s take tuple t1= (1, 3, 4, 2, 5) and t2=( 6, 7, 8, 9)
Function Description Example
Returns length of the
len() len( t1) =5
tuple or size of the tuple
return maximum element
max(tuple) max( t1) = 5
of given tuple
return minimum element
min(tuple) min( t1) = 1
of given tuple
Sums up the numbers in
sum(tuple) sum( t1) = 15
the tuple
input elements in the x=sorted( t1)
sorted(tuple) tuple and return a new print(x)
sorted list O/P: (1, 2, 3, 4, 5)
Explain Nested Tuple with example. SUMMER-2022
Nested Tuple
A nested tuple is a Python tuple that has been placed inside of another tuple.
Example:
tup=(1,2,(11,12,13),3,4)
print(tup[2])
print(tup[2][2])
print("printing complete tuple")
for i in tup:
print(i)
O/P:
(11, 12, 13)
13
printing complete tuple
1
2
(11, 12, 13)
3
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 28
Advanced Python Programming (UNIT-1) | 4321602
Give the difference between Tuple and List in python. SUMMER-2022, SUMMER-
2023
Difference between list and tuple
Sr.
List Tuple
No.
The literal syntax of list is shown by The literal syntax of tuple is shown by
1 the [ ]. the ( ).
2 List are mutable Tuples are immutable
3 Iterations are time-consuming Iterations are comparatively Faster
Inserting and deleting items is easier Inserting and deleting items is not
4 with a list. possible with tuple.
5 Lists consume more memory Tuple consumes less than the list
A tuple does not have many built-in
6 Lists have several built-in methods.
methods because of immutability
A unexpected change or error is In a tuple, changes and errors don't
7 more likely to occur in a list. usually occur because of immutability.
8 The list has the variable length The tuple has the fixed length
What is Dictionary in Python? Write a program to concatenate two dictionary into new
one. SUMMER-2022
Write down the properties of dictionary in python. SUMMER-2022
Dictionary
Dictionaries are used to store data values in key : value pairs where the values can be any
Python object, The keys, in contrast, are immutable Python objects, such as strings,
tuples, or numbers.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 29
Advanced Python Programming (UNIT-1) | 4321602
dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(dict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
O/P:
Empty Dictionary:
{}
Example:
Employee = {"Name": "Johnny", "Age": 32, "salary":26000}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
O/P:
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000}
Accessing the dictionary values
The keys of the dictionary can be used to obtain the values because they are unique from one
another. The following method can be used to access dictionary values.
Example:
Employee = {"Name": "Dev", "Age": 20, "salary":45000}
print(type(Employee))
print("printing Employee data .... ")
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 30
Advanced Python Programming (UNIT-1) | 4321602
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
O/P:
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its
values. Dict[key] = value and the value can both be modified.
An existing value can also be updated using the update() method.
Example:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'pink'
Dict[2] = 'black'
Dict[3] = 'blue'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values with a single Key
Dict['value'] = 20, 33, 24
Print(Dict)
Dict[3]=’yellow’
O/P:
Empty Dictionary:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 31
Advanced Python Programming (UNIT-1) | 4321602
{}
Dictionary after adding 3 elements:
{0: 'pink', 2: 'black', 3: 'blue'}
{0: 'pink', 2: 'black', 3: 'blue', 'value': (20, 33, 24)}
after updating value
{0: 'pink', 2: 'black', 3: 'yellow', 'value': (20, 33, 24)}
Example 2:
Employee = {"Name": "Dev", "Age": 20, "salary":45000}
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
print("printing the new data");
print(Employee)
O/P:
printing Employee data ....
{'Name': 'Dev', 'Age': 20, 'salary': 45000}
Enter the details of the new employee....
Name: abc
Age: 20
Salary: 1200
printing the new data
{'Name': 'abc', 'Age': 20, 'salary': 1200}
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Example:
Employee = {"Name": "Dev", "Age": 30, "salary":55000}
print(type(Employee))
print("printing Employee data .... ")
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 32
Advanced Python Programming (UNIT-1) | 4321602
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["salary"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
O/P:
<class 'dict'>
printing Employee data ....
{'Name': 'Dev', 'Age': 30, 'salary': 55000}
Deleting some of the employee data
printing the modified information
{'Age': 30}
Deleting the dictionary: Employee
Lets try to print it again
NameError : name 'Employee' is not defined
using pop() Method
The pop() method accepts the key as an argument and remove the associated value.
Example:
Dict1 = {"Name": "Dev", "Age": 30, "salary":55000}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(“Age”)
print(Dict1)
O/P:
{'Name': 'Dev', 'salary': 55000}
Iterating Dictionary
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 33
Advanced Python Programming (UNIT-1) | 4321602
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
O/P:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000}
for x in Employee:
print(Employee[x])
O/P:
John
29
25000
Example - 3
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000}
for x in Employee.values():
print(x)
O/P:
John
29
25000
Example 4
#for loop to print the items of the dictionary by using items() method
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 34
Advanced Python Programming (UNIT-1) | 4321602
Employee = {"Name": "John", "Age": 29, "salary":25000}
for x in Employee.items():
print(x)
O/P:
('Name', 'John')
('Age', 29)
('salary', 25000)
Properties of Dictionary Keys
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than
one value for a single key, then the value which is last assigned is considered as the value of
the key.
Example:
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
"John"}
for x, y in Employee.items():
print(x,y)
O/P:
Name John
Age 29
Salary 25000
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be
used as the key, however mutable objects like lists cannot be used as the key in a dictionary.
Example:
Employee = {"Name": "John", "Age": 29, "salary":26000, "Company":"WIPRO",
[100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
O/P:
TypeError: unhashable type: 'list'
List out built-in Dictionary functions. Write a program to demonstrate the dictionaries
functions and operations. SUMMER-2023
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 35
Advanced Python Programming (UNIT-1) | 4321602
Built-in Dictionary Functions and Methods
Take dic ={ 1:”black”,2:”white”,3:”yellow”}
Function Description Example
len() It is used to calculate the length of the len(dic) = 3
dictonary
dic.clear()
Remove all the elements from the
dic.clear()
dictionary print(dic) O/P: { }
dic1=dic.copy()
print(dic1)
dict.copy() Returns a copy of the dictionary
O/P: {1: 'black', 2: 'white', 3:
'yellow'}
print(dic.items())
Returns a list containing a tuple for each O/P: dict_items([(1, 'black'),
dict.items()
key value pair
(2, 'white'), (3, 'yellow')])
print(dic.keys())
dict.keys() Returns a list containing dictionary’s keys
O/P: dict_keys([1, 2, 3])
print(dic.values ())
Returns a list of all the values of O/P: dict_values(['black',
dict.values()
dictionary
'white', 'yellow'])
print( dic.pop(1))
dict.pop() Remove the element with specified key
O/P: black
print( dic.popItem())
dict.popItem() Removes the last inserted key-value pair
O/P: (3, 'yellow')
dic.update({4:’pink’})
Updates the dictionary with the specified O/P: {1: 'black', 2: 'white', 3:
dict.update()
key-value pairs
'yellow',4:’pink’}
Write a program to concatenate the following dictionaries to create a new one. Sample
Dictionary: dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result: {1:
10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}. WINTER-2022
dic1={1:10, 2:20}
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 36
Advanced Python Programming (UNIT-1) | 4321602
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic={}
for d in (dic1,dic2,dic3):
dic.update(d)
print(dic)
O/P:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
**********
“Do not give up, the beginning is always hardest!”
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 37