Why tuple is not a immutable type?! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why tuple is not a immutable type?!

I've been doing a challenge that had the question: "which data type os a immutable type" and the options were set, tuple, dict and float. I choose tuple and it was wrong. WHY?!

8th Dec 2018, 1:01 PM
Matheus Andrade
Matheus Andrade - avatar
4 Answers
+ 6
Can you take a screenshot of the question? Is it one of those questions where multiple options may be correct, and we'd have to select all of them? If it is, then that could explain why you were wrong: both tuple and float are immutable. But a few more words must be said. Though a tuple is immutable, it can contain mutable elements like lists: a = (1, 2, [3]) Now even though we can't do something like a[2] = [5], we can modify the list in a[2] by doing, say, a[2].append(4). Another fun fact is that a tuple of numbers is hashable, but a tuple containing a list isn't (so it can't serve as a dictionary key or be an element of a set).
8th Dec 2018, 1:40 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
From the docs: "The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable." https://docs.python.org/3/reference/datamodel.html
8th Dec 2018, 1:42 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
Matheus Andrade oh right sorry I misread the question...... well maybe it referred to its elements ? (Which can be mutable....)
8th Dec 2018, 1:56 PM
Uni
Uni - avatar
+ 3
Uni, what you said is exactly the reason for a tuple being immutable. But answering the question it said it was wrong
8th Dec 2018, 1:41 PM
Matheus Andrade
Matheus Andrade - avatar