Computer Science

Can you change an element of a sequence? What if a sequence is a dictionary? What if a sequence is a tuple?

Python Tuples

2 Likes

Answer

Yes, we can change any element of a sequence in python only if the type of the sequence is mutable.

  1. 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}
  2. 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

Answered By

2 Likes


Related Questions