17.6 Modifying a Tuple

Modifying a Tuple

Tuples are immutable. However, it can hold mutable objects, which means we can do this:

tup = (7, 'coffee', ['good', 'morning'])
tup[2][1] = 'evening'  # changes 'morning' to 'evening'
print(tup)  # prints (7, 'coffee', ['good', 'evening'])

but not this:

tup = (7, 'coffee', ['good', 'morning'])
tup[0] = 5  # tries to change 7 to 5
# Above code results in
# TypeError: 'tuple' object does not support item assignment

View on GitHub

Basically, you can modify mutable objects in the tuple but not the tuple itself. That means that you can’t increase or decrease how many elements there are in a tuple, and you can’t replace elements inside a tuple.

Go here (https://www.programiz.com/python-programming/tuple) for additional information on tuples.


Modify Tuple

Given a tuple whose first two elements are strings and the third element is a dictionary. Add the given key and value to the dictionary in the tuple.

Previous Section

Next Section


Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.