Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 11, CBSE
Assertion (A): Tuple in Python is an ordered and immutable data type.
Reasoning (R): Tuples can contain heterogenous data and permit duplicate values as well.
Both A and R are true but R is not the correct explanation of A.
Explanation
Tuples in Python are ordered, meaning elements are arranged in a specific sequence, and this order cannot be changed. Tuples are immutable, so once a tuple is created, we cannot add, change, or update its elements. Duplicate values can be included in a tuple. Additionally, a tuple can hold values of different data types, making it heterogeneous in nature.
Consider the given two statements:
Statement 1: t1 = tuple('python')
Statement 2: t1[4] = 'z'
Assertion (A): The above code will generate an error.
Reasoning (R): Tuple is immutable by nature.
Both A and R are true and R is the correct explanation of A.
Explanation
The statement t1 = tuple('python')
creates a tuple t1
from the string 'python', resulting in t1
being ('p', 'y', 't', 'h', 'o', 'n'). The statement t1[4] = 'z'
attempts to modify the element at index 4 of the tuple, which is not allowed because tuples are immutable in Python. Hence, it raises an error.
Assertion (A): In Python, tuple is an immutable sequence of data.
Reasoning (R): Immutable means that any change or alteration in data is mentioned in the same place. The updated collection will use the same address for its storage.
A is true but R is false.
Explanation
In Python, tuples are immutable or unmodifiable, so once a tuple is created, we cannot add, change, or update its elements.
Consider the given statements for creating dictionaries in Python:
D1 = { 'A' : 'CS' , 'B' : ' IP' }
D2 = { 'B' : 'IP', 'A' : 'CS ' }
Assertion (A): Output of print(D1==D2) is True.
Reasoning (R): Dictionary is a collection of key-value pairs. It is not a sequence.
Both A and R are true but R is not the correct explanation of A.
Explanation
The output of print(D1 == D2)
is True. In Python, dictionaries are considered equal if they have the same keys and corresponding values, regardless of the order of the key-value pairs. Since D1
and D2
have the same keys with the same values, the comparison returns True. Dictionary is a collection of key-value pairs. It is not a sequence.
Assertion (A): Dictionaries are enclosed within curly braces { }.
Reasoning (R): The key-value pairs are separated by commas (,).
Both A and R are true but R is not the correct explanation of A.
Explanation
Dictionaries in Python are enclosed within curly braces {}, where each key is separated from its corresponding value by a colon (:), and different key-value pairs are separated by commas.
Assertion (A): The pop() method can be used to delete elements from a dictionary.
Reasoning (R): The pop() method deletes the key-value pair and returns the value of deleted element.
Both A and R are true and R is the correct explanation of A.
Explanation
The pop()
method is used to delete elements from a dictionary. This method not only deletes the item specified by the key from the dictionary but also returns the deleted value.
Assertion (A): Keys of the dictionaries must be unique.
Reasoning (R): The keys of a dictionary can be accessed using values.
A is true but R is false.
Explanation
The keys of dictionaries in Python must be unique and immutable. Values in a dictionary can be accessed using their corresponding keys.
Assertion (A): clear() method removes all elements from the dictionary.
Reasoning (R): len() function cannot be used to find the length of a dictionary.
A is true but R is false.
Explanation
The clear()
method removes all items from the particular dictionary and returns an empty dictionary. The len()
method returns the length of key-value pairs in the given dictionary.
All of these
Reason — Python dictionaries are unordered collections of items where each item is a mapping of unique keys to values and dictionaries are mutable.
tup[2] = 56
Reason — Tuples in Python are immutable. Therefore, attempting to assign a new value to an existing element, such as tup[2] = 56
, will result in an error.
False
Reason — In tuple, the comparison operator starts by comparing the first element from each sequence. If they are equal, it goes on to the next element, and so on, until it finds elements that differ. Since tup1
is (1, 2, 4, 3) and tup2
is (1, 2, 3, 4), the third element of tup1
(which is 4) is greater than the third element of tup2
(which is 3). Hence, tup1
is not less than tup2
, so the comparison evaluates to False.
T = (4, )
Reason — In Python, to create a tuple with a single element, we need to include a trailing comma after the element. This tells Python that we are defining a tuple rather than just using parentheses for grouping. Thus, T = (4, )
creates a tuple with one element.
del D1["Red"]
Reason — The syntax to delete a key-value pair from a dictionary in Python is : del dictionary_name[key]
. Therefore, according to this syntax, del D1["Red"]
is correct statement.
False
Reason — In Python, dictionary keys are case-sensitive. The dictionary D1
has the key "Virat" with an uppercase 'V', but the check is for "virat" with a lowercase 'v'. Since "virat" does not match the case of the key "Virat", the expression "virat" in D1
evaluates to False.
Similarities:
Both tuples and lists maintain the order of elements.
Both support indexing and slicing to access and manipulate subsets of their elements.
Both can store elements of different data types, including numbers, strings, and other objects.
Both tuples and lists can be iterated over using loops.
Differences:
Tuples are immutable, while lists are mutable.
Tuples are enclosed in parentheses (), while lists are enclosed in square brackets [].
Tuples use less memory whereas lists use more memory.
We can use tuples in dictionary as a key but it is not possible with lists.
We cannot sort a tuple but in a list we can sort by calling "list.sort()" method.
We cannot remove an element in a tuple but in list we can remove an element.
We cannot replace an element in a tuple but we can replace in a list.
Tuple | Dictionary |
---|---|
Tuples are ordered collection of elements. | Dictionaries are unordered collection of key-value pairs. |
Tuples are immutable. | Dictionaries are mutable. |
Tuples are enclosed in parentheses (). | Dictionaries are enclosed in curly braces {}. |
Elements of tuples can be accessed by index. | The items in a dictionary are accessed by keys. |
Strings | Tuples |
---|---|
A sequence of characters used to represent text. | An ordered collection of elements that can include different data types. |
Strings are defined using single quotes ' ', double quotes " ", or triple quotes ''' ''' for multi-line strings. | Tuples are defined using parentheses (). |
False, we can have different type of values in a tuple. A tuple can hold values of different data types, i.e., a tuple is heterogeneous in nature.
For example: T1 = (1, 'apple', [2, 3])
.
A nested tuple is a tuple that contains other tuples as its elements. When we add one or more tuples inside another tuple, the items in the nested tuples are combined together to form a new tuple.
For example,
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'book')
tuple3 = (tuple1, tuple2)
print(tuple3)
((0, 1, 2, 3), ('python', 'book'))
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
dict_keys([1, 2, 3, 4])
dict_values(['one', 'two', 'three', 'four'])
6
d1.items()
— Returns a list of tuples containing the key-value pairs in d1
.d1.keys()
— Returns a list of all the keys in d1
.d1.values()
— Returns a list of all the values in d1
.d1.update(d2)
— Updates d1
with key-value pairs from d2
. After this operation, d1
contains {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}.len(d1)
— Returns the number of key-value pairs in d1
, which is 6 after updating.{1: 'one', 2: 'two', 4: 'four'}
'four'
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 8: ' eight'}
{}
del d1[3]
: Removes the key 3 and its corresponding value 'three' from d1
. After deletion, d1
contains {1: 'one', 2: 'two', 4: 'four'}.d1.pop(4)
: Removes the key 4 and its corresponding value 'four' from d1
. After popping, d1
is {1: 'one', 2: 'two'}.d1[8] = 'eight'
: Adds a new key-value pair 8: 'eight' to d1
. Now d1
becomes {1: 'one', 2: 'two', 8: 'eight'}.d1.clear()
: Clears all key-value pairs from d1
, resulting in an empty dictionary {}
.The code will result in an Error because the multiplication operator * is being used incorrectly between a tuple and a string. The multiplication operator * in Python is used to repeat the elements of a tuple a certain number of times, but the number of repetitions must be an integer, not a string.
The code will result in an Error because the number of variables on the left side of the assignment (X, Y, Z) does not match the number of elements in the tuple t1
.
The max()
function should be used within parentheses in the print
statement. Additionally, for the max()
function to work, all elements in the tuple must be of the same type; otherwise, Python cannot compare them, leading to an Error.
The code will result in an Error because tuples in Python are immutable. The line t[1] = 'o'
attempts to modify the second element of the tuple, which is not allowed because tuples do not support item assignment.
The code raises an error because T1
is not recognized as a tuple but as a string due to the missing comma. A single-element tuple needs a trailing comma, like T1 = ('A',)
. Therefore, T1
is a string, and concatenating a string with a tuple using T1 + T2
is not allowed, causing the error.
The code will result in an Error because the number of variables on the left side of the assignment does not match the number of values on the right side.
t1 = (100, 200, "Global", 3, 3.5, "Exam", [1, 2], (30, 40), (3, 5, 3)) :
Consider the above tuple 't1' and answer the following questions:
(a) len(t1)
(b) 20 not in t1
(c) t1[-8:-4]
(d) t1[5:]
(e) t1.index(5)
(f) t1.index(3, 6)
(g) 10 in t1
(h) t1.count(3)
(i) any(t1)
(j) t1[2]*2
(a) len(t1) — 9
(b) 20 not in t1 — True
(c) t1 [-8:-4] — (200, 'Global', 3, 3.5)
(d) t1 [5:] — ('Exam', [1, 2], (30, 40), (3, 5, 3))
(e) t1.index (5) — It raises an error.
(f) t1.index (3, 6) — It raises an error.
(g) 10 in t1 — False
(h) t1.count (3) — 1
(i) any (t1) — True
(j) t1[2]*2 — GlobalGlobal
Explanation
(a) The len()
function returns the number of elements in the tuple. Hence, len(t1)
returns 9.
(b) The not in
operator checks if an element is not present in the tuple. Hence, 20 not in t1
returns True because 20 is not an element of the tuple t1
.
(c) It uses negative indexing to select elements from the 8th position from the end to the 4th position from the end.
(d) This slices the tuple starting from the index 5 to the end.
(e) The index()
method returns the first index of the specified element. Hence, t1.index(5)
raises an Error because 5 is not an element of the tuple.
(f) It raises an error because there is no occurrence of the element 3 after index 6.
(g) The in
operator checks if a specified value is present in the tuple. For 10 in t1
, it returns False because 10 is not an element of the tuple t1
.
(h) The count()
method returns the number of occurrences of 3 in the tuple. Hence, t1.count(3)
returns 2 because 3 appears twice in the tuple.
(i) The any()
function in Python is a built-in function that returns True if at least one element in a given iterable (such as a list, tuple, or set) is True. If all elements are False, it returns False. Hence, any(t1)
returns True because the elements in the tuple are True.
(j) The statement t1[2]
is accessing the third element of the tuple t1
, which is the string "Global". The statement t1[2]*2
is attempting to multiply the accessed element by 2. However, since the element is a string, it will repeat the string "Global" twice, resulting in "GlobalGlobal".
(a)
(10, 20, 30, 40)
(100, 200, 300)
In the code t1, t2 = t2, t1
, Python performs tuple unpacking and assignment simultaneously. This means that t1
is assigned the value of t2
, and t2
is assigned the value of t1
. As a result, t1
becomes (10, 20, 30, 40) and t2
becomes (100, 200, 300).
(b)
True
The code print(t1 != t2)
compares the tuples t1
and t2
to check if they are not equal. Since t1
is (100, 200, 300) and t2
is (10, 20, 30, 40), they have different lengths and different elements. Therefore, it evaluates to True.
(c)
False
The code print(t1 < t2)
compares the tuples t1
and t2
element by element. Since t1 = (100, 200, 300)
and t2 = (10, 20, 30, 40)
, the comparison starts with the first elements, where 100 < 10 is False. Therefore, the tuple t1
is not less than t2
, and the code prints False.
WAP to accept values from a user. Add a tuple to it and display its elements one by one. Also display its maximum and minimum value.
t1 = eval(input("Enter a tuple: "))
t2 = (10, 20, 30)
t3 = t1 + t2
print("Elements of the combined tuple:")
for element in t3:
print(element)
print("Maximum value:", max(t3))
print("Minimum value:", min(t3))
Enter a tuple: (11, 67, 34, 65, 22)
Elements of the combined tuple:
11
67
34
65
22
10
20
30
Maximum value: 67
Minimum value: 10
Write a Python program to input any values for two tuples. Print it, interchange it, and then compare them.
t1 = eval(input("Enter the first tuple: "))
t2 = eval(input("Enter the second tuple: "))
print("Original Tuples:")
print("Tuple 1:", t1)
print("Tuple 2:", t2)
t1, t2 = t2, t1
print("\nSwapped Tuples:")
print("Tuple 1 (after swapping):", t1)
print("Tuple 2 (after swapping):", t2)
if t1 == t2:
print("\nThe swapped tuples are equal.")
else:
print("\nThe swapped tuples are not equal.")
Enter the first tuple: (5, 6, 3, 8, 9)
Enter the second tuple: (77, 33, 55, 66, 11)
Original Tuples:
Tuple 1: (5, 6, 3, 8, 9)
Tuple 2: (77, 33, 55, 66, 11)
Swapped Tuples:
Tuple 1 (after swapping): (77, 33, 55, 66, 11)
Tuple 2 (after swapping): (5, 6, 3, 8, 9)
The swapped tuples are not equal.
Write a Python program to input 'n' classes and names of their class teachers to store it in a dictionary and display the same. Also, accept a particular class from the user and display the name of the class teacher of that class.
n = int(input("Enter number of classes: "))
data = {}
for i in range(n):
class_name = input("Enter class name: ")
teacher_name = input("Enter teacher name: ")
data[class_name] = teacher_name
print("Class data:", data)
find = input("Enter a class name to find its teacher: ")
if find in data:
print("Teacher for class", find, "is", data[find])
else:
print("Class not found in the data.")
Enter number of classes: 4
Enter class name: green
Enter teacher name: Aniket
Enter class name: yellow
Enter teacher name: Pratibha
Enter class name: red
Enter teacher name: Mayuri
Enter class name: blue
Enter teacher name: Prithvi
Class data: {'green': 'Aniket', 'yellow': 'Pratibha', 'red': 'Mayuri', 'blue': 'Prithvi'}
Enter a class name to find its teacher: red
Teacher for class red is Mayuri
Write a program to store students' names and their percentage in a dictionary, and delete a particular student name from the dictionary. Also display dictionary after deletion.
n = int(input("Enter number of students: "))
data = {}
for i in range(n):
stu_name = input("Enter student name: ")
percentage = input("Enter percentage: ")
data[stu_name] = percentage
print("Student data:", data)
find = input("Enter a student name to delete: ")
if find in data:
del data[find]
print("Updated student data:", data)
else:
print("Student not found in the data.")
Enter number of students: 4
Enter student name: Megha
Enter percentage: 98
Enter student name: Amit
Enter percentage: 88
Enter student name: Nitin
Enter percentage: 92
Enter student name: Amulya
Enter percentage: 79
Student data: {'Megha': '98', 'Amit': '88', 'Nitin': '92', 'Amulya': '79'}
Enter a student name to delete: Nitin
Updated student data: {'Megha': '98', 'Amit': '88', 'Amulya': '79'}
Write a Python program to input names of 'n' customers and their details like items bought, cost and phone number, store it in a dictionary and display all the details in a tabular form.
n = int(input("Enter the number of customers: "))
customer_data = {}
for i in range(n):
name = input("Enter customer name: ")
items_bought = input("Enter items bought: ")
cost = float(input("Enter cost: "))
phone_number = int(input("Enter phone number: "))
customer_data[name] = {
'Items Bought': items_bought,
'Cost': cost,
'Phone Number': phone_number
}
print("Customer Details:")
print("Name\t\tItems Bought\t\tCost\t\tPhone Number")
for name, details in customer_data.items():
print(name, "\t\t", details['Items Bought'], "\t\t", details['Cost'], "\t\t", details['Phone Number'])
Enter the number of customers: 4
Enter customer name: Sakshi
Enter items bought: Chocolate, Icecream
Enter cost: 200
Enter phone number: 9876354678
Enter customer name: Shashank
Enter items bought: Biscuits, Maggie, Soup
Enter cost: 450
Enter phone number: 8976346378
Enter customer name: Saanvi
Enter items bought: Veggies, Coffee
Enter cost: 300
Enter phone number: 8794653923
Enter customer name: Shivank
Enter items bought: Door mat, Bottles, Boxes
Enter cost: 600
Enter phone number: 6737486827
Customer Details:
Name Items Bought Cost Phone Number
Sakshi Chocolate, Icecream 200.0 9876354678
Shashank Biscuits, Maggie, Soup 450.0 8976346378
Saanvi Veggies, Coffee 300.0 8794653923
Shivank Door mat, Bottles, Boxes 600.0 6737486827