KnowledgeBoat Logo
OPEN IN APP

Chapter 8

Tuples and Dictionary

Class 11 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

Elements in a tuple can be of Dissimilar type.

Question 2

Tuples are indexed by an integer.

Question 3

Tuples are immutable, you cannot update or edit the elements.

Question 4

tuple() function is used to convert a sequence data type into tuple.

Question 5

Like lists, Dictionaries are mutable which means they can be changed.

Question 6

A Python dictionary is a mapping of unique keys to values.

Question 7

The association of a key and a value is called a Key-Value pair.

Question 8

To create a dictionary, key-value pairs are separated by comma.

Question 9

In key-value pair, each key is separated from its value by a colon(:).

Question 10

keys() function returns the keys of the dictionary.

Question 11

The Del<dict> statement removes a dictionary object along with its items.

Question 12

popitem() function will delete the last inserted key-value pair from the dictionary.

State True or False

Question 1

An element in a dictionary is a combination of key-value pairs.

Answer

True

Reason — In a dictionary, an element is a combination of key-value pairs.

Question 2

Internally, dictionaries are indexed on the basis of values.

Answer

False

Reason — The elements in a dictionary are indexed by keys and not values.

Question 3

We can repeat a key in dictionary.

Answer

False

Reason — Keys are unique and immutable in a dictionary.

Question 4

In dictionary, two unique keys can have the same values.

Answer

True

Reason — In a dictionary, while each key must be unique, multiple keys can have the same value.

Question 5

A tuple can be used as the key in a dictionary if it contains immutable elements.

Answer

True

Reason — A tuple can be used as a key in a dictionary if all the elements within the tuple are immutable. This is because dictionary keys must be unique and immutable.

Question 6

clear() is used to delete a dictionary.

Answer

False

Reason — The clear() method is used to remove all items from the particular dictionary and returns an empty dictionary.

Question 7

A tuple is a mutable data type.

Answer

False

Reason — A tuple is an immutable data type. Once a tuple is created, we cannot add, change or update its elements.

Question 8

List can be used as keys in a dictionary.

Answer

False

Reason — Lists cannot be used as keys in a dictionary because they are mutable. Dictionary keys must be immutable.

Question 9

Updating an element in a dictionary at runtime is possible.

Answer

True

Reason — Updating an element in a dictionary at runtime is possible because dictionaries are mutable data structures.

Question 10

We can create immutable dictionaries in Python.

Answer

False

Reason — We cannot create immutable dictionaries in Python because dictionaries are mutable.

Question 11

A tuple can store elements of different data types.

Answer

True

Reason — A tuple can store elements of different data types, i.e., a tuple is heterogeneous in nature.

Question 12

A tuple cannot store list as an element.

Answer

False

Reason — A tuple can store a list as an element. While the tuple is immutable, it can contain mutable elements like lists.

Question 13

Creating individual values from a tuple's elements is called packing.

Answer

False

Reason — Creating individual values from a tuple's elements is called unpacking.

Question 14

We cannot delete a dictionary once created.

Answer

False

Reason — We can delete a dictionary in Python using the del statement.

Multiple Choice Questions

Question 1

Which of the statement(s) is/are correct?

  1. Python Dictionary is an unordered collection of items.
  2. Python Dictionary is a mapping of unique keys to values.
  3. Dictionary is mutable.
  4. All of these

Answer

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.

Question 2

If tup = (20, 30, 40, 50), which of the following is incorrect?

  1. print (tup[3])
  2. tup[2] = 56
  3. print (max(tup))
  4. print (len(tup))

Answer

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.

Question 3

Consider two tuples given below:

tup1 = (1, 2, 4, 3) 
tup2 = (1, 2, 3, 4) 

What will the following statement print: print (tup1 < tup2)

  1. True
  2. False
  3. Error
  4. None of these

Answer

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.

Question 4

Which function returns the number of elements in the tuple?

  1. len()
  2. max()
  3. min()
  4. count()

Answer

len()

Reason — The len() function returns the number of elements in the tuple.

Question 5

To create an empty dictionary, we use the statement as:

  1. d1 = {}
  2. d1 = []
  3. d1 = ()
  4. d1 == {}

Answer

d1 = {}

Reason — The statement to create an empty dictionary in Python is d1 = {}.

Question 6

In a dictionary, the elements are accessed through:

  1. Key
  2. Value
  3. Index
  4. None of these

Answer

Key

Reason — In a dictionary, elements are accessed using keys, which uniquely identifies each element's associated value.

Question 7

Keys of a dictionary must be:

  1. Similar
  2. Unique
  3. Both (i) and (ii)
  4. All of these

Answer

Unique

Reason — Keys of a dictionary must be unique and immutable.

Question 8

To create a new dictionary with no items:

  1. Dict
  2. dict()
  3. d1=[]
  4. None of these

Answer

dict()

Reason — The function dict() is used to create a new dictionary with no items.

Question 9

Which function is used to return a value for the given key?

  1. len()
  2. get()
  3. keys()
  4. None of these

Answer

get()

Reason — The get() method returns a value for the given key. If key is not available, then returns the default value None.

Question 10

Which function is used to remove all items from a particular dictionary?

  1. clear()
  2. pop()
  3. delete()
  4. rem()

Answer

clear()

Reason — The clear() function is used to remove all items from the particular dictionary and returns an empty dictionary.

Question 11

Which one of the following is correct to insert a single element in a tuple?

  1. T = 4
  2. T = (4)
  3. T = (4, )
  4. T = [4, ]

Answer

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.

Question 12

Which of the following functions will return key-value pairs of the dictionary?

  1. key()
  2. values()
  3. items()
  4. get()

Answer

items()

Reason — The items() function returns the content of dictionary as a list of tuples having key-value pairs.

Question 13

Which of the following will delete key-value pair for key = "Red" from a dictionary D1 ?

  1. delete D1("Red")
  2. del.D1("Red")
  3. del D1["Red"]
  4. del D1

Answer

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.

Question 14

What will be the output?

D1 = { "Rahul":56, "Virat":99} 
print("virat" in D1)
  1. True
  2. False
  3. No output
  4. Error

Answer

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.

Question 15

Which of the following creates a tuple?

  1. t1 = ("a", "b")
  2. t1 [2]= ("a", "b")
  3. t1= (5) *2
  4. None of these

Answer

t1 = ("a", "b")

Reason — The statement t1 = ("a", "b") creates a tuple with two elements: "a" and "b".

Assertions and Reasons

Question 1

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.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 2

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.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 3

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.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 4

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.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 5

Assertion (A): Dictionaries are enclosed within curly braces { }.

Reasoning (R): The key-value pairs are separated by commas (,).

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 6

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.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 7

Assertion (A): Keys of the dictionaries must be unique.

Reasoning (R): The keys of a dictionary can be accessed using values.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Question 8

Assertion (A): clear() method removes all elements from the dictionary.

Reasoning (R): len() function cannot be used to find the length of a dictionary.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

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.

Solutions to Unsolved Questions

Question 1

What advantages do tuples have over lists?

Answer

The advantages of tuples over lists are as follows:

  1. Tuples use less memory whereas lists use more memory.

  2. We can use tuples in dictionary as a key but it is not possible with lists.

Question 2

What are the similarities and differences between tuples and lists?

Answer

Similarities:

  1. Both tuples and lists maintain the order of elements.

  2. Both support indexing and slicing to access and manipulate subsets of their elements.

  3. Both can store elements of different data types, including numbers, strings, and other objects.

  4. Both tuples and lists can be iterated over using loops.

Differences:

  1. Tuples are immutable, while lists are mutable.

  2. Tuples are enclosed in parentheses (), while lists are enclosed in square brackets [].

  3. Tuples use less memory whereas lists use more memory.

  4. We can use tuples in dictionary as a key but it is not possible with lists.

  5. We cannot sort a tuple but in a list we can sort by calling "list.sort()" method.

  6. We cannot remove an element in a tuple but in list we can remove an element.

  7. We cannot replace an element in a tuple but we can replace in a list.

Question 3

What is a key-value pair in dictionary?

Answer

A key-value pair in a dictionary is an association of a key and its corresponding value.

Question 4

What are the differences between tuple and dictionary?

Answer

TupleDictionary
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.

Question 5

What are the differences between strings and tuples?

Answer

StringsTuples
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 ().

Question 6

Can we always have same type of values in a tuple? State True or False with justification.

Answer

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]).

Question 7

What is nested tuple? Explain with example.

Answer

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)
Output
((0, 1, 2, 3), ('python', 'book'))

Question 8

Write the code to create an empty tuple.

Answer

t = tuple()

Question 9

Write a Python program to create a tuple with different data types and display.

Answer

t = tuple((42, "Hello, World!", 3.14, True, [1, 2, 3]))
print(t)
Output
(42, 'Hello, World!', 3.14, True, [1, 2, 3])

Question 10

What is the difference between "book" and ('book',)?

Answer

The difference between "book" and ('book',) is that "book" is a string, representing a sequence of characters, while ('book',) is a tuple with a single element.

Question 11

Write a Python program to combine first 3 elements and last 3 elements from a tuple.

T1 = ('a', 1, 2, 3, 4, 'b', 'c', 'book', 10)

Output should be:

('a', 1, 2, 'c', 'book', 10)

Answer

T1 = ('a', 1, 2, 3, 4, 'b', 'c', 'book', 10)
first_three = T1[:3]
last_three = T1[-3:]
result = first_three + last_three
print(result)
Output
('a', 1, 2, 'c', 'book', 10)

Question 12(a)

Find errors and rewrite the same after correcting the following code:

d1 = {1:10, 2.5:20, 3:30, 4:40, 5:50, 6:60, 7:70}

Answer

The given code is syntactically correct and doesn't contain any errors.

Question 12(b)

Find errors and rewrite the same after correcting the following code:

d1(9) = 90 

Answer

In Python, we assign the key-value pair using square brackets [], not parentheses ().

The corrected code is:

d1[9] = 90

Question 12(c)

Find errors and rewrite the same after correcting the following code:

del d1(2)  

Answer

In Python, to delete an element from a dictionary, we should use square brackets [], not parentheses ().

The corrected code is:

del d1[2]

Question 12(d)

Find errors and rewrite the same after correcting the following code:

pop d1[4]

Answer

Th syntax of pop() method is dictname.pop(key).

The corrected code is:

d1.pop(4)

Question 12(e)

Find errors and rewrite the same after correcting the following code:

d1.item()

Answer

The correct method to retrieve all key-value pairs from a dictionary is items(), not item().

The corrected code is:

d1.items()

Question 12(f)

Find errors and rewrite the same after correcting the following code:

d1.key()

Answer

The correct method to retrieve all keys from a dictionary is keys(), not key().

The corrected code is:

d1.keys()

Question 12(g)

Find errors and rewrite the same after correcting the following code:

d1.value()

Answer

The correct method to retrieve all values from a dictionary is values(), not value().

The corrected code is:

d1.values()

Question 12(h)

Find errors and rewrite the same after correcting the following code:

d1.gets(4, 80) 

Answer

The correct method to retrieve a value for a given key is get(), not gets().

The corrected code is:

d1.get(4, 80)

Question 12(i)

Find errors and rewrite the same after correcting the following code:

d1.len()

Answer

The syntax of len() function is len(dict).

The corrected code is:

len(d1)

Question 12(j)

Find errors and rewrite the same after correcting the following code:

d1.clears()  

Answer

The correct method to clear all elements from a dictionary is clear(), not clears().

The corrected code is:

d1.clear()

Question 13(a)

Suppose

>>> d1 = { 1 : 'one' , 2: 'two' , 3: 'three' , 4: 'four'}
>>> d2 = { 5 :'five', 6:'six' }

Write the output of the following code:

>>> d1.items() 
>>> d1.keys() 
>>> d1.values() 
>>> d1.update(d2)
>>> len(d1)

Answer

Output
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
dict_keys([1, 2, 3, 4])
dict_values(['one', 'two', 'three', 'four'])
6
Explanation
  1. d1.items() — Returns a list of tuples containing the key-value pairs in d1.
  2. d1.keys() — Returns a list of all the keys in d1.
  3. d1.values() — Returns a list of all the values in d1.
  4. 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'}.
  5. len(d1) — Returns the number of key-value pairs in d1, which is 6 after updating.

Question 13(b)

Suppose

>>> d1 = { 1 : 'one' , 2: 'two' , 3: 'three' , 4: 'four'}
>>> d2 = { 5 :'five', 6:'six' }

Write the output of the following code:

>>> del d1[3] 
>>> print(d1) 
>>> d1.pop(4) 
>>> print(d1) 
>>> d1 [8] =' eight'
>>> print(d1) 
>>> d1.clear() 
>>> print(d1)

Answer

Output
{1: 'one', 2: 'two', 4: 'four'}
'four'
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 8: ' eight'}
{}
Explanation
  1. del d1[3]: Removes the key 3 and its corresponding value 'three' from d1. After deletion, d1 contains {1: 'one', 2: 'two', 4: 'four'}.
  2. d1.pop(4): Removes the key 4 and its corresponding value 'four' from d1. After popping, d1 is {1: 'one', 2: 'two'}.
  3. d1[8] = 'eight': Adds a new key-value pair 8: 'eight' to d1. Now d1 becomes {1: 'one', 2: 'two', 8: 'eight'}.
  4. d1.clear(): Clears all key-value pairs from d1, resulting in an empty dictionary {}.

Question 14(a)

Consider the following code and find out the error:

tup1 = (10, 20, 30)        
tup2 = tup1 * (3, )  

Answer

The code will result in an Error because the multiplication operation between a tuple and another tuple is not valid in Python.

Question 14(b)

Consider the following code and find out the error:

tup1 = ('a', 'b', 'c')  
tup1 = tup1 + d

Answer

The code will result in an Error because the variable d is not defined before it is used in the expression tup1 + d.

Question 14(c)

Consider the following code and find out the error:

tup1 = ("Riya", ) * '4'

Answer

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.

Question 14(d)

Consider the following code and find out the error:

t1 = (10, 20, 30, 40) 
X, Y, Z = t1

Answer

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.

Question 14(e)

Consider the following code and find out the error:

tup1=('A', 'school', 10.5, 70)
print max(tup1) 

Answer

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.

Question 14(f)

Consider the following code and find out the error:

t = (10, 20, 30, 40)
t[1] = 'o'

Answer

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.

Question 14(g)

Consider the following code and find out the error:

T1 = ('A')
T2 = ('B', 'C', 3)
T3 = T1 + T2

Answer

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.

Question 14(h)

Consider the following code and find out the error:

T1 = (10, 20, 30, 40)
T2 = (40, 50, 60)
T1, T2, T3 = T1, T2

Answer

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.

Question 15

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

Answer

(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".

Question 16

Write the output of the following statements:

(a) >>> tuple([10,20,40])

(b) >>> ("Tea",)*5

(c) >>> tuple ("Item")

Answer

(a)

Output
(10, 20, 40) 

(b)

Output
('Tea', 'Tea', 'Tea', 'Tea', 'Tea')

(c)

Output
('I', 't', 'e', 'm')

Question 17

Consider two tuples t1 & t2 given below:

t1 = (100, 200, 300)
t2 = (10, 20, 30, 40)

Write the output of the following statements:

(a)

t1, t2 = t2, t1  
print(t1)   
print (t2)

(b) print (t1!=t2)

(c) print (t1 < t2)

Answer

(a)

Output
(10, 20, 30, 40)
(100, 200, 300)
Explanation

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)

Output
True
Explanation

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)

Output
False
Explanation

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.

Question 18

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.

Solution
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))
Output
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

Question 19

Write a Python program to input any values for two tuples. Print it, interchange it, and then compare them.

Solution
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.")
Output
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.

Question 20

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.

Solution
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.")
Output
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

Question 21

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.

Solution
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.")
Output
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'}

Question 22

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.

Solution
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'])
Output
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
PrevNext