8
Question Question 8
Can you change an element of a sequence? What if a sequence is a dictionary? What if a sequence is a tuple?
Yes, we can change any element of a sequence in python only if the type of the sequence is mutable.
- Dictionary — We can change the elements of a dictionary as dictionary is a mutable sequence. For example:
d = {'k1':1, 'k2':4}
d['k1'] = 2
Here, we are changing the value of first key-value pair of dictionary d. Now dictionary d will be :{'k1':2, 'k2':4} - Tuple — We cannot change the elements of a tuple as tuple is an immutable sequence.
For example:
tup = (1, 2, 3, 4)
tup[0] = 5
The above expression will give an error.TypeError: 'tuple' object does not support item assignment