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?
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
Related Questions
How is indexing of a dictionary different from that of a list or a string?
What do you understand by ordered collection and unordered collection ? Give examples.
How do you add key:value pairs to an existing dictionary?
Which of the following types qualify to be the keys of a dictionary?
- String
- tuple
- Integer
- float
- list
- dictionary