CBSE Class 11 Computer Science Question 7 of 112

Dictionaries — Question 7

Back to all questions
7
Question

Question 7

Can you change an element of a sequence or collection? What if a collection is a dictionary? What if a sequence is a string?

Answer

Elements of a collection or sequence can be changed only if the collection or sequence is mutable. Hence, for dictionaries, the elements can be changed as dictionaries are mutable but for strings is cannot be changed as strings are immutable.

Example:

>>> d = {1 : 'a', 2: 'b'}
>>> d[1] = 'c'
>>> str = "hello"
>>> str[1] = "python"
Output
{1: 'c', 2: 'b'}
TypeError: 'str' object does not support item assignment