Unit 4 - v2-1
Unit 4 - v2-1
UNIT IV
TUPLES, SETS and DICTIONARIES
TUPLES:
➢ Tuple is an immutable ordered collection of elements enclosed in round brackets and
separated by commas
➢ A tuple can have heterogeneous data items (i.e) a tuple can have string and list as data
items as well.
Creating a Tuple:
Creating a tuple is very simple and almost similar to creating a list. For creating atuple,
generally you need to just put the different comma-separated values within a parentheses
as shown below.
Syntax:
Tuple_name = (val 1, val2,...)
where val (or values) can be an integer, a floating number, a character, or a string.
Examples:
1. R=( )
print( R )
Output: ( )
2. T1= ( 1, 2 )
print( T1 )
Output: 1 2
Index in a tuple starts at 0 and operations like slice, concatenate can be performed on a tuple.
For example, to access values in tuple, slice operation is used along with the index or indices
to obtain value stored at that index
N = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Updating Tuple:
Since Tuple is immutable , we can only extract values from one tuple into another tuple
Output:
1.5 , 2.6 , 5.7 , 10, 20, 30
Since tuple is immutable, when we try to delete the element from Tuple it will raise an error
Example 1
T = (1,2,3,4,5,6,7,8,9,10)
del T[1]
print (T)
Output:
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: 'tuple' object doesn't support item deletion
Example 2
K=(1,2,3,4,5,6,7,8,9,10)
del K
print(K)
Output:
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name ‘K' is not defined
1. Concatenation operation
2. Repetition operation
3. Membership operation
4. Iteration
5. Comparison
6. Length – len() function
7. Maximum- max() function
8. Minimum – min() function
9. sum() function
10.all( ) function
11.any() function
12.sorted() function
13.Convert sequence into Tuple-tuple() function
1. Concatenation:
D= (1,2,3,4,5)
E =( 10,20,30,40,50)
F=D + E
print(F))
Y=(‘a’,’b’,’c’) + (1.2,3.7,8.3)
print(Y)
Output:
(1, 2, 3, 4, 5, 10, 20, 30, 40, 50)
('a', 'b', 'c', 1.2, 3.7, 8.3)
2. Repetition
Repeats the element in the Tuple
U = (1, 2, 3)
print(U*3)
Output:
123123123
3. Membership Operation
True
False
4. Iteration
T = (10,20,30,40,50)
for var in T:
print(T.index(var),var)
Output:
0 10
1 20
2 30
3 40
4 50
5. Comparison
tuple1 = (1,2,3)
tuple2 = (1,2,4)
print (tuple1 == tuple2)= False
print (tuple1 < tuple2) = True
print (tuple1 > tuple2) = False
6. len( ):
H = (1,2,3,4,5)
print(len(H))
Output:
5
7. max():
Output:
90
8. min():
Output:
7
9. sum()
tup = (5,10,1,3)
sum(tup)
Output:
19
10. all() :
Returns True if all elements of the tuple are true
x=(1,2,3,4)
all(x)
Output:
True
11. any() :
Returns True if any of the elements of the tuple are true
x=(1,0,3,4)
any(x)
Output:
True
12. sorted ( ) : Returns a new sorted tuple
x=(34,5,17,9)
sorted(x)
Output:
(5, 9, 17, 34)
g = (1, 2, 3, 4)
t="Hello“
h=tuple(g)
j=tuple(t)
print(h)
print(j)
Output :
(1, 2, 3, 4)
('H', 'e', 'l', 'l', 'o')
Tuple Assignment:
Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the
left side of the assignment operator to be assigned values from a tuple given on the right side
of the assignment operator.
Each value is assigned to its respective variable. In case, an expression is specified on the
right side of the assignment operator, first that expression is evaluated and then assignment is
done.
1.( a ,b, c ) = (1 ,2 , 3 )
print( a, b , c)
Output:1 2 3
def max_min( L ):
x=max(L)
y=min(L)
return(x,y)
S=( 1 ,2, 3, 4, 5, 6, 7, 8, 9, 10 )
i, j= max_min(S)
Print(Highest value:”,i)
Print(“Lowest Value:”,j)
Output:
Highest value: 10
Lowest Value: 1
Nested Tuples:
2.F = ( “Hello”, [ 1, 2, 3, 4, 5] )
print(F[0]) = Hello
print(F[1]) = 12345
print(F[1][2]) = 3
print(F[0][0]) = H
Tuple Methods
1. count( ) :
Syntax :
tuple.count(value)
E = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = E.count(5)
print(x)
Output:
2
2.index( ):
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
Syntax :
tuple.index(value)
S = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = s.index(8)
print(x)
Output:
3
Example 1:
S = (9,3)
q , r = divmod(*S)
print(q, r)
Output:
3 0
Example 2:
S = (9,3)
q , r = divmod(S)
print(q, r)
Output:
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
TypeError: divmod expected 2 arguments, got 1
The zip() is a built-in function that takes two or more sequences and "zips" them into a
list of tuples. The tuple thus, formed has one element from each sequence.
Syntax:
zip(iterator1, iterator2, iterator3 ...)
T = (1,2,3,4,5)
C=[‘a’,’b’,’c’,’d’,’e’]
print(list((zip(T,C)))
Output:
[(1,’a’),(2,’b’),(3,’c’),(4,’d’),(5,’e’)]
SETS:
Set is a datatype in python which is mutable and unordered collections of elements without
duplicates.
Syntax:
set_variable={val1, val2,...}
Example:
s={1, 2.0,"abc"}
List1=[1,2,3,4,5,6,5,4,3,2,1]
print(set(List1))
Tup1=('a','b','c','d','b','e','a')
print(set(Tup1))
str="abcdefabcdefg"
print(set(str))
print(set("she sells sea shells".split()))
Output:
{1,2,3,4,5,6}
{'a','c','b','e','d'}
{'a','c','b','e','d','f','g'}
{'sells','she','sea','shells'}
1. Comparision :
s==t and s!=t
s==t returns True if the two sets are equivalent and False otherwise.
s! =t returns True if both the sets are not equivalent and False otherwise.
Example:
s={'a', 'b','c'}
t={"abc"}
z=set(tuple('abc'))
print(s==t)
print(s!=z)
Output:
False
False
2. membership :
The membership operator "in" returns true if the given element is present in the set and
false if it is not present.
The membership operator "not in" returns true if the given element is not present in set s and
false if the given element is present.
Example:
s={1,2,3,4,5}
print(3 in s)
print(3 not in s)
Output:
True
False
Example:
s={1,2,3,4,4,5}
print(len(s))
Output:
5
Example:
s={1,2,3,4,5}
print(max(s))
t={'a', 'c', 'b'}
print(max(t))
Output:
5
C
5. min() :
Returns the minimum value in the set.
Example:
s={0, 1,2,3}
print(min(s))
t={'a', 'b', 'c'}
print(min(t))
Output:
0
a
s={1,2,3,4,5}
print(sum(s))
Output:
15
7. all() : Returns True if all elements in the set are True and False otherwise.
Example:
s={0, 1,2}
t={-1, 1,2.0}
print(all(s))
print(all(t))
Output:
False
True
8. any() :
Returns True if any of the elements in the set is True.
Returns False if the set is empty.
Example:
s={ }
t={1, -2, 2.0}
print(any(s))
print(any(t))
Output:
False
True
9. sorted():
Returns a new sorted list from elements in the set.
Example:
s={5,2,1,4,3}
t={'c', 'a', 'd', 'b'}
print(sorted(s))
print(sorted(t))
Output:
[1,2,3,4,5]
['a', 'b', 'c', 'd']
10.set ( ) : Creates a set object.The items in a set list are unordered, so it will appear in
random order.
Example :
x = set(("apple", "banana", "cherry"))
print(x)
Output:
Set Methods
1.update(): Adds the given elements to the set without duplicates.
Syntax: s.update(sequence)
Example:
s=set([1,2,3,4,5])
t=set([6,7,8])
s.update(t)
print(s)
Output:
{1,2,3,4,5,6,7,8}
Syntax: s.add(value)
Example:
s=set([1,2,3,4,5])
s.add(6)
print(s)
Output:
{1,2,3,4,5,6}
3.remove(): Removes only one element from set s.It returns KeyError if the given element
is not present in set s.
Syntax: s.remove(Value)
Example:
s=set([1,2,3,4,5])
s.remove(4)
print(s)
Output:
{1,2,3,5}
4.discard():
Removes only one element from the set s.It does not return error if the given element is not
present in set.
Syntax: s.discard(Value)
Example:
s={1,2,3,4,5}
s.discard(3)
print(s)
Output:
{1,2,4,5}
5.pop() :
Removes and returns any random elements from set s. Key error is raised if set s is empty.
Syntax: s.pop()
Example:
s={1,2,3,4,5}
s.pop()
print(s)
Output:
{1,2,3,4,}
6.clear() :
Removes all elements from the set.
Syntax: s.clear()
Example:
s=set([1,2,3,4,5])
s.clear()
print(s)
Output:
set()
7.copy() :
Syntax: s.copy()
Example:
s={1,2,3}
t={4, 5,6}
print(s.copy())
Output:
{1,2,3}
8. issubset() or s<=t
Returns True if every element in set s is present in set t and False otherwise.
Syntax: s.issubset(t)
Example:
s={1,2,3,4,5}
t={1,2,3,4,5,6,7,8}
print(s<=t)
Output:
True
9. issuperset() or s>=t
Returns True if every element in t is present in s and False otherwise.
Syntax: s.issuperset(t)
Example:
s={1,2,3,4,5}
t={1,2,3,4,5,6,7,8,9,10}
print(s.superset(t))
Output:
False
10.union() or s|t: Returns a set s that has elements from both set s and t.
Syntax: s.union(t)
Example:
s={1,2,3}
t={1,2,3,4,5}
print(s|t)
Output:
{1,2,3,4,5}
11.intersection() or s&t :
Returns a new set that has elements which are common to both the sets s and t.
Syntax: s.intersection(t)
Example:
s={1,2,3,4}
t={3,4,5}
z=s&t
print(z)
Output:
{3, 4}
12.intersection_update():
Returns a set that has elements which are common to both the sets s and t
Syntax: s.intersection_update(t)
Example:
s={1,2,3,4}
t={3,4,5}
s.intersection_update(t)
print(s)
Output:
{3, 4}
13.difference() or s-t:
Returns a new set that has elements in set s but not in set t.
Syntax: s.difference(t) (or) s-t
Example:
s={1,2,3,5,10}
t={1,5,3,2,8}
z=s-t
print(z)
Output:
{10}
14.difference_update():
Syntax: s.difference_update(t)
Example:
s={1,2,3,4,5,6,12}
t={1,2,3,4,5,6,7,8,9,10}
s.difference_update(t)
print(s)
Output:
{12}
15.symmetric_difference(t) or s^t:
Returns a new set with elements either in s or in t but not both.
Example:
s={1,2,3,4,5,10}
t={1,2,3,4,5,6,7,8,9,10}
z=s^t
print(z)
Output:
{6,7,8,9}
16.isdisjoint():
Syntax: s.isdisjoint(t)
Example:
s={1,2,3}
t={4,5,6}
print(s.isdisjoint(t))
Output:
True
17.enumerate():
Returns an enumerate object which contains index as well as value of all the items of set
as a pair.
Syntax: enumerate(s)
Example 1:
s={'a','b','c','d'}
print(list(enumerate(s)))
Output:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Example 2:
s={'a','b','c','d'}
for i in enumerate(s):
print(i)
Output:
(0, 'a')
(1, 'c')
(2, 'b')
(3, 'd')
Dictionaries:
• Dictionaries are unordered collection of data values. Data values are stored in key-
value pair.
• Dictionaries are Python’s built-in mapping type. They map keys, which can be any
immutable type, to values, which can be any type, just like the values of a list or tuple.
• Dictionaries cannot have duplicate keys.
Creating a Dictionary:
❖ One way to create a dictionary is to start with the empty dictionary and add key-
value pairs. The empty dictionary is denoted {}:
Syntax:
Example:
T= { }
R={ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}
print(T)
print(R)
Output:
{ }
The key-value pairs of the dictionary are separated by commas. Each pair contains a key
and a value separated by a colon.
The order of the pairs may not be what you expect. Python uses complex algorithms to
determine where the key-value pairs are stored in a dictionary.
❖ Another way to create a dictionary is to provide a list of key-value pairs using the
same syntax as the previous output:
It doesn’t matter what order we write the pairs. The values in a dictionary are accessed
with keys, not with indices, so there is no need to care about ordering.
Accesing values in dictionary:
The value in the dictionary is accessed using its key not by the index value.
If u try access the value with its key not available in the dictionary it will raise a keyerror.
Example:
Output:
1
Hari
Traceback (most recent call last):
File "./prog.py", line 5, in <module>
KeyError: 'dept'
To a new value in dictionary specify key-value pair with the existing Dictionary name..
Syntax:
Dictionary_name[‘key’:’value’]
Example:
Output:
Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’ Mark:98
Output:
Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’ Mark:100
inventory={'apples':430,'bananas':312,'oranges':525,'pears':217}
print (inventory)
{'oranges':525,'apples':430,'pears':217,'bananas':312}
If someone buys all of the pears, we can remove the entry from the dictionary:
del inventory['pears']
print (inventory)
{'oranges':525,'apples':430,'bananas':312}
Output:
Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in <module>
print(R) #this will cause an error because “R" no longer exists.
NameError: name ‘R' is not defined
dict={'Rollno':1,'Name':'Arav','Course':'B.Tech'}
for k in dict: #Accessing keys
print(k)
Output:
Rollno
Name
Course
for k in dict.values( ): #Accessing values
print(k)
Output:
1
Arav
B.Tech
Output:
Rollno 1
Name Arav
Course B.Tech
Nested Dictionary:
A dictionary inside another dictionary is called nested dictionary.
student={‘Shiv’:{‘pspp’:98,’Physics’:100,’BEEE’:95},
‘Sasi’:{‘pspp’:100,’Physics’:97,’BEEE’:94},
‘Bobby’:‘pspp’:99,’Physics’:93,’BEEE’:91}}
Output:
Shiv {'pspp': 98, 'Physics': 100, 'BEEE': 95}
Sasi {'pspp': 100, 'Physics': 97, 'BEEE': 94}
Bobby {'pspp': 99, 'Physics': 93, 'BEEE': 91}
100
String Formatting With Dictionary:
student={'Arav':'B.Tech','Harini':'MBBS'}
for x,y in student.items():
print("%s studying in %s" % (x,y) )
Output:
Arav studying in B.Tech
Harini studying in MBBS
1. Membership:The ‘in’ and ‘not in’ operators on a Python dictionary to check whether it
contains a certain key.
h={1: 1, 2: 2, 3: 3}
print(2 in h)
print(4 not in h)
Output:
True
True
Output:
Length : 4
1. fromkeys(): The dict.fromkeys() method creates a new dictionary from the given
iterable (string, list, set, tuple) as keys and with the specified value.
Example1:
keys = {'Mumbai','Bangalore','Chicago','New York'}
value = 'city'
dictionary = dict.fromkeys(keys, value)
print(dictionary)
Output:
{'New York': 'city', 'Bangalore': 'city', 'Mumbai': 'city', 'Chicago': 'city'}
Example2:
D = dict.fromkeys(['Bob', 'Sam'], 'Developer')
print(D)
Output:
{'Bob': 'Developer', 'Sam': 'Developer'}
Example 1
myDict = dict(a=1, b=2, c=3, d=4)
print(myDict)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Example 2
Output:
{'a': 1, 'b': 2, 'c': 3}
3. pop() :Removes the item with the specified key name
K={ "brand": "Ford", "model": "Mustang", "year": 1964 }
K.pop("model")
print( K )
Output:
{'brand': 'Ford', 'year': 1964}
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Output:
{}
Syntax
dictionary.copy()
Syntax
dictionary.get(keyname, value)
8.setdefault():Returns the value of the item with the specified key. If the key does not
exist, insert the key, with the specified value,
Syntax: dictionary.setdefault(keyname, value)
Example1:
Example2:
romanNums = {'I':1, 'II':2, 'III':3}
value = romanNums.setdefault('IV')
print("The return value is: ",value)
print("Updated dictionary: ",romanNums)
Output:
The return value is: None
Updated dictionary:
{'I': 1, 'II': 2, 'III': 3, 'IV': None}
9.update():Updates the dictionary with the elements from another dictionary object or
from an iterable of key/value pairs.
Syntax: dict.update(iterable)
Output:
Original Dictionary: {'A': 'Apple', 'B': 'Ball'}
Dictionary after updation: {'A': 'Apple', 'B': 'Bat'}
Output:
Original Dictionary: {'A': 'Apple'}
Dictionary after updation: {'A': 'Apple', 'B': 'ball', 'C': 'Cat'}
10.items(): Returns a view object which contains the key-value pairs of the dictionary, as
tuples in a list.
Syntax: dictionary.items()
11.keys():Returns a view object which contains the keys of the dictionary, as a list.
The view object will reflect any changes done to the dictionary, see example below.
Syntax
dictionary.keys()
car = { "brand": "Ford", "model": "Mustang", "year": 1964 }
car["color"] = "white"
x = car.keys()
print(x)
Output:
(['brand', 'model', 'year', 'color'])
12.values():Returns a view object which contains the values of the dictionary, as a list. The
view object will reflect any changes done to the dictionary, see example below.
Syntax
dictionary.values()
Output:
dict_values(['Ford', 'Mustang', 2018])
Output:
{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Banana': 'In stock'}
Dictionary comprehension technique is used to convert a Python list to a dictionary using the
same values.
A dictionary comprehension is similar to a list comprehension but Dictionary
comprehensions use pointed brackets ({}) whereas list comprehensions use square brackets
([]).
Example:
fruits = ["Apple", "Pear", "Peach", "Banana"]
fruit_dictionary = { fruit : "In stock" for fruit in fruits }
print(fruit_dictionary)
Output:
{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Banana': 'In stock'}
Zip( ) function to convert two lists into a dictionary. One list is used as the keys for the
dictionary and the other as the values.
Example:
Output:
{'Apple': 0.35, 'Pear': 0.4, 'Peach': 0.4, 'Banana': 0.28}
Example:
t=((1,'a'), (2,'b'))
print(dict(t))
Output:
{1: 'a', 2: 'b'}
Example:
t=((1,'a'), (2,'b'))
dict((y, x) for x, y in t)
print(dict(t))
Output:
{1: 'a', 2: 'b'}
2.Using dict():
You can use the combination of dict(), map(), and reversed() method to convert a tuple to the
dictionary. The map() method returns a map object, which is an iterator. The reversed()
function returns the reversed iterator of the given sequence.
Example:
Output:
((11, 'eleven'), (21, 'mike'), (19, 'dustin'), (46, 'caleb'))
{11:'eleven', 21:'mike', 19:'dustin', 46:'caleb'}
The setdefault() function searches for a key and displays its value, and creates a new key
with def_value if the key is not present. See the following code.
Example:
x=((1,”stars”),(2,”moon”),(3,”sun”))
dict = { }
for i,j in x:
dict.setdefault(i,[]).append(j)
print(dict)
Output:
{1: [“stars”], 2: [“moon”], 3: [“sun”]}
Example:
Output:
{'Boba': [21], 'Din': [19], 'Grogu': [46], 'Ahsoka': [11]}
{'Boba': [21], 'Din': [19], 'Grogu': [46], 'Ahsoka': [11]}
Illustrative Programs:
Output:
Sorted array [7,9,10,11,12,16]
2.Python program for implementation of Insertion Sort
a=[42,33,19,55,16]
print(“Sorted array is: “, insertion_sort(a))
Output:
Sorted array is : [16,19,33,42,55]
1. Split the unsorted list until it contains single element in the sublist
2. Compare each of the element and group them as sorted
3. Repeat step 2 until whole list is merged and sorted
Program:
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i<len(lefthalf) and j <len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
k=k+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j <len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
Output:
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Splitting [46]
Merging [14, 46]
Splitting [43, 27]
Splitting [43]
Splitting [27]
Merging [27, 43]
Merging [14, 27, 43, 46]
Splitting [57, 41, 45, 21, 70]
Splitting [57, 41]
Splitting [57]
Splitting [41]
Merging [41, 57]
Splitting [45, 21, 70]
Splitting [45]
Splitting [21, 70]
Splitting [21]
Splitting [70]
Merging [21, 70]
Merging [21, 45, 70]
Merging [21, 41, 45, 57, 70]
Merging [14, 21, 27, 41, 43, 45, 46, 57, 70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]
plt.xlabel('percentage')
plt.ylabel('No.of students')
plt.title('Histogram')
plt.show()
Output:
5. Write a python program to plot a line graph
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
plt.plot(Year, Unemployment_Rate)
plt.title('Unemployment Rate Vs Year')
plt.xlabel('Year')
plt.ylabel('Unemployment Rate')
plt.show()
Output
6. Write a Python program to compute element-wise sum of given tuples.
x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("Original lists:")
print(x)
print(y)
print(z)
print("\nElement-wise sum of the said tuples:")
result = tuple(map(sum, zip(x, y, z)))
print(result)
Output:
Original lists:
(1, 2, 3, 4)
(3, 5, 2, 1)
(2, 2, 3, 1)
Element-wise sum of the said tuples:
(6, 9, 8, 6)
def string_list_to_tuple(str1):
result = tuple(x for x in str1 if not x.isspace())
return result
str1 = "python 3.0"
print("Original string:")
print(str1)
print(type(str1))
print("Convert the said string to a tuple:")
print(string_list_to_tuple(str1))
print(type(string_list_to_tuple(str1)))
Output:
Original string:
python 3.0
<class 'str'>
Convert the said string to a tuple:
('p', 'y', 't', 'h', 'o', 'n', '3', '.', '0')
<class 'tuple'>
8. Write a Python program to check if two given sets have no elements in
common.
x = {1,2,3,4}
y = {4,5,6,7}
z = {8}
print("Original set elements:")
print(x)
print(y)
print(z)
print("\nConfirm two given sets have no element(s) in
common:")
print("\nCompare x and y:")
print(x.isdisjoint(y))
print("\nCompare x and z:")
print(z.isdisjoint(x))
print("\nCompare y and z:")
print(y.isdisjoint(z))
Output:
Original set elements:
{1, 2, 3, 4}
{4, 5, 6, 7}
{8}
Compare x and y:
False
Compare x and z:
True
Compare y and z:
True
9. Write a Python program to remove the intersection of a 2nd set from the 1st
set.
sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("Original sets:")
print(sn1)
print(sn2)
print("\nRemove the intersection of a 2nd set from the 1st set
using difference_update():")
sn1.difference_update(sn2)
print("sn1: ",sn1)
print("sn2: ",sn2)
sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("\nRemove the intersection of a 2nd set from the 1st set
using -= operator:")
sn1-=sn2
print("sn1: ",sn1)
print("sn2: ",sn2)
Output:
Original sets:
{1, 2, 3, 4, 5}
{4, 5, 6, 7, 8}
Remove the intersection of a 2nd set from the 1st set using difference_update():
sn1: {1, 2, 3}
sn2: {4, 5, 6, 7, 8}
Remove the intersection of a 2nd set from the 1st set using -= operator:
sn1: {1, 2, 3}
sn2: {4, 5, 6, 7, 8}
for i in str:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
return d
print(lettercount("python prog"))
Output:
Program:
def lsum(l):
sum=0
for i in l:
if type(i)== list:
sum=sum+lsum(i)
else:
sum=sum+i
return sum
lst=[1,2,[3,4],[5,6,7],8]
print(lsum(lst))
Output:
36