Computer Science
Can you change an element of a sequence? What if a sequence is a dictionary? What if a sequence is a tuple?
Answer
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
Related Questions
How do you create the following tuples?
(a) (4, 5, 6)
(b) (-2, 1, 3)
(c) (-9, -8, -7, -6, -5)
(d) (-9, -10, -11, -12)
(e) (0, 1, 2)
If a = (5, 4, 3, 2, 1, 0) evaluate the following expressions:
(a) a[0]
(b) a[1]
(c) a[a[0]]
(d) a[a[-1]]
(e) a[a[a[a[2]+1]]]
What does a + b amount to if a and b are tuples?
What does a * b amount to if a and b are tuples?