KnowledgeBoat Logo

Computer Science

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

Python Dictionaries

CBSE

2 Likes

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   

Answered By

2 Likes


Related Questions