Python Lab-Book Assignment 3
Python Lab-Book Assignment 3
Python Tuple:
A Tuple is a collection of Python objects separated by commas or written in round
brackets.
Ex >>>T1=“Hi”, “Hello”
>>>print(T1) #output: ( ‘Hi’, ‘Hello’)
>>>T2=(10,20,4.5,”Monday”)
>>>print(T2) #output: (10,20,4.5,’Mondy’)
Tuples are sequences, just like lists. The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
>>>print(T1[0]) #’Hi’
>>>print(T1[-1]) #’Hello’
>>>T1[0]=“Bye” #Error
Add Items:
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items:
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely: The del keyword can delete the tuple completely
Ex. >>>T1=(10,20)
>>>del T1
In-Built Tuple Functions:
1. cmp(): Python tuple method cmp() compares elements of two tuples.
syntax: cmp(tuple1, tuple2) cmp function return 0 if two tuples are same, 1 if
elements of first tuple is greater than elements of second tuple, otherwise -1
2. len(tuple): It is used to calculate the length of the tuple
>>>T1=(10,20,30)
>>>print(len(T1)) #3
3. max(Tuple): It returns the maximum element of the tuple.
4. min(Tuple): It returns the minimum element of the tuple.
>>>print(max(T1) #30
>>>print(min(T1)) #10
5. sum(tuple): Return sum of all elements within tuple
>>> print(sum(T1)) #60
6. all(tuple): it returns True if all the items in the tuple are true, otherwise it returns false.
If the tuple is empty, the function also returns true.
>>>T1=(10,20,30) T2=(10,0,20)
>>>print(all(T1)) #True
>>>print(all(T2)) #False
7. any(): Python any() function accepts iterable (list, tuple, dictionary etc.) as an
argument and return true if any of the element in iterable is true, else it returns false. If
iterable is empty then any() method returns false.
>>>print(any(T1)) #True
8. tuple(seq): It converts any sequence to the tuple.
>>>str=“Python”
>>>T1=tuple(str)
>>>print(T1) #(‘P’,’y’,’t’,’h’,’o’,’n’)
9. tuple.count(obj.): It returns the number of occurrences of the specified object in the
tuple. >>>L1=(10,20,40,10,20)
>>>print(L1.count(20)) #2
10. tuple.index(obj): It retuurns the lowest index in the tuple that object appears.
>>>T1=(10,20,30,20)
>>> print(T1.index(20)) #1
Packing and Unpacking:
In tuple packing, we place value into a new tuple while in tuple unpacking we extract
those values back into variables.
Ex >>> t=(101,”Nilesh”,80.78) #tuple packing
>>> (rollno, name, marks)=t #tuple unpacking
>>> print(rollno) # 101
>>>print(name, marks) #Nilesh 80.78
Python Set:
The set in python can be defined as the unordered collection of various items enclosed
within the curly braces. The elements of the set can not be duplicate. The elements of the
python set can not be changed.There is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print
them all together or we can get the list of elements by looping through the set.
Creating a set:
The set can be created by enclosing the comma separated items with the curly braces.
Python also provides the set method which can be used to create the set by the passed
sequence.
The difference_update():
The set difference_update() method modifies the existing set.
If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed,
then B gets modified into ( B – A).
Ex. >>>a={1,2,3,4,5}; b={3,4,5,6}
>>>a.difference_update(b)
>>>print(a) #{1,2}
The symmetric_difference():
This in-built function of Python Set helps us to get the symmetric difference between two
sets, which is equal to the elements present in either of the two sets, but not common to
both the sets. >>>print(a.symmetirc_difference(b)) #{1,2,6}
issuperset() in Python:
The issuperset() method returns True if all elements of a set A occupies set B which is
passed as an argument and returns false if all elements of B not present in A.
This means if A is a superset of B then it returns true; else False
Syntax: A.issuperset(B) checks whether A is a superset of B or not. True if A is a superset
of B; otherwise false.
Ex >>>A={1,2,3,4,5}; B={2,3,4}
>>>A.issuperset(B)
#True >>>B.issuperset(A)
#False issubset() in python:
returns true if first set is a subset of seconds set otherwise false
>>> A.issubset(B) #False
>>>B.issubset(A) #True
Python Dictionary:
Dictionary in Python is an unordered collection of items in the form of key-value pair.
Dictionary holds key : value pair.
Each key-value pair in a Dictionary is separated by a colon :, whereas each item is
separated by a ‘comma’.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers
and tuples, but the values associated with key can be repeated and be of any type.
In Python, a Dictionary can be created by placing sequence of elements within curly {}
braces, separated by ‘comma’.
Ex >>> d={1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}
>>>print(d) #{1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}
Rollno 101
Marks 80.75
8. Printing individual values of dictionary using format specifier:
>>> d={“Rollno”:101, “Name”:“Nilesh”, “Marks”:80.75}
>>> print("Roll No=%d"%d["Rollno"])
Roll No=101
>>> print("Name of student=
%s"%d["Name"]) Name of
student=Nilesh
>>> print("Marks Obtained=%f"%d["Marks"])
Marks Obtained=80.750000
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.
>>>D={ } # empty dictionary
>>>D=dict({1:”Hi”,2:”Hello”})
>>>print(D) #{1:”Hi”,2:”Hello”}
Note – Dictionary keys are case sensitive, same name but different cases of Key
will be treated distinctly.
Updating Dictionary:
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
Ex. >>> d={1: “One”, 2: “Two”}
>>>print(d) #{1: 'One', 2: 'Two‘}
>>>d[2]=“Twelve”
>>>print(d) #{1: 'One', 2: 'Tweleve'}
>>>d[3]=“Three”
>>>print(d) #{1: 'One', 2: 'Tweleve', 3: 'Three'}
Properties of Dictionary:
1. In the dictionary, we can not store multiple values for the same keys.
If we pass more than one values for a single key, then the value which is last
assigned is considered as the value of the key.
>>>d={"RN":101,"Name":"Suresh","Marks":80,"Name":"Rajesh"}
>>> print(d) #{'Name': 'Rajesh', 'RN': 101, 'Marks': 80}
2. In python, the key cannot be any mutable object.
We can use numbers, strings, or tuple as the key but we can not use any mutable
object like the list as the key in the dictionary.
3. Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.
Assignments:
Practice Set:
1. Write a Python program to add and remove operation on set.
2. Write a Python program to do iteration over sets.
3. Write a Python program to find the length of a set.
4. Write a Python program to create a tuple with numbers and print one item.
5. Write a Python script to add a key to a dictionary. Sample Dictionary : {0: 10, 1:
20}
Expected Result : {0: 10, 1: 20, 2: 30}
Set A:
1. Write a Python program to find maximum and the minimum value in a set.
# Create a set
my_set = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
# Item to add
item_to_add = 6
# Create a new tuple by concatenating the original tuple with a new tuple
containing the item
new_tuple = my_tuple + (item_to_add,)
# Join the string representations of the tuple elements into a single string
result_string = ''.join(tuple_as_strings)
# Key to check
key_to_check = 'age'
# Sample dictionary
Output:
Set B:
1. Write a Python program to create set difference and a symmetric difference.
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Find the set difference (elements in set1 but not in set2) using the difference()
method
difference_result = set1.difference(set2)
# Find the symmetric difference (elements in either set1 or set2, but not in both)
using the symmetric_difference() method
symmetric_difference_result = set1.symmetric_difference(set2)
2. Write a Python program to create a list of tuples with the first element as the
number and second element as the square of the number.
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Create a list of tuples where the first element is the number and the second
element is its square
result = [(num, num ** 2) for num in numbers]
4. Write a Python program to get the 4th element from front and 4th element from
last of a tuple.
# Create a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Element to check
element_to_check = 3
# Check if the element exists in the tuple using the 'in' keyword
if element_to_check in my_tuple:
print(f"{element_to_check} exists in the tuple.")
else:
print(f"{element_to_check} does not exist in the tuple.")
Output:
3 exists in the tuple.
# Sample dictionaries
result_dict.update(dic2)
result_dict.update(dic3)
Output:
# Add an element to the original set to demonstrate that the copies are
shallow
original_set.add(6)
# Input dictionaries
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}