Page 452 - Computer Science V2.0 Class 11
P. 452
7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.
Ans. A tuple once created cannot be changed Even if you try to make changes in the tuple and give it the same name, Python Internally will
create a new tuple and store it at a different memory location. For example:
myTuple = (1,2,'orangebooks')
print("id before:",id(myTuple))
print(myTuple)
myTuple += ('ncert solution','XI','computer','science')
print("id after:",id(myTuple))
print(myTuple)
Output: id before: 2531242116928
(1, 2, 'orangebooks')
id after: 2531236739488
(1, 2, 'orangebooks', 'ncert solution', 'XI', 'computer', 'science')
Check the id printed in two different statement. As you can observe in both cases variable name is the same but it is printed different ids,
It means that tuple is immutable data type, and if you try to change it, it will not make the change in-place, it create a new variable.
8. TypeError occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Ans. tuple1 = (5) statement does not create a tuple type variable, it creates integer type variable. len() function works with collection/
sequence type variable such tuple, list, dictionary, string.
len() function need sequence value or variable as argument. That’s why len(tuple1) generate an error TypeError.
Corrected Way :
tuple1 = (5,) #statement 1
len(tuple1) #statement 2
Output:
1
PROGRAMMING PROBLEMS
1. Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the
usernames from the email IDs and second to store domain names from the email IDs. Print all three tuples at the end of the program.
[Hint: You may use the function split()]
Ans. emailIDs = ()
num = int(input("Enter the number of Email IDs you want to add: "))
for i in range(1, num+1):
email = input("Enter email id of student" +str(i)+" : ")
emailIDs += (email,)
userNameTuple = ()
domainTuple =()
for email in emailIDs:
lst = email.split('@')
userNameTuple += (lst[0],)
domainTuple += (lst[1],)
print("Tuple of usernames:")
print(userNameTuple)
print("Tuple of Domain Names:")
print(domainTuple)
438 Touchpad Computer Science (Ver. 2.0)-XI

