0

I understand that tuples are immutable objects. Therefore I cannot change an element of a tuple (unless I create a new tuple). However, if I have:

my_tuple = (1, 2, [3, 4])

and then I try to modify the 3rd element only with the extend() method:

my_tuple[2].extend([5, 6])

I see that my tuple is now (1, 2, [3, 4, 5, 6]) and python doesn't throw an error. I understand I have modified a list, which is mutable. But the list is inside the tuple, so it should be immutable. Doesn't this behaviour violate the immutability of tuples?

user12394113
  • 381
  • 3
  • 13
  • 1
    You just mutated the list object inside the tuple. You did not change the tuple in any way. – Ch3steR May 10 '20 at 17:18
  • 1
    Immutable is that you can't modidy it's own properties : length, but the object inside get their own properties – azro May 10 '20 at 17:20
  • short answer: The tuple is immutable, but its elements aren't necessarily – wjandrea May 10 '20 at 17:28

1 Answers1

-1

List is mutable and tuple is immutable.

In the above extend method, you modify the list.

To better understand this:

iIf you define a dictionary, like so:

a={} a[my_tuple]=0

you will get error because of immutable object, i.e tuple, contains a mutable object that is list.

So a dictionary key is not hashable but if you define:

my_tuple=(1,2,3)

then a[my_tuple] will not give an error.

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • 1
    Please [edit] to add punctuation - this is very hard to read. Using [code formatting](/editing-help#code) would help a lot too. BTW welcome to SO! Check out the [tour] and [answer] if you want more advice. – wjandrea May 10 '20 at 17:32
  • Also, hashability is closely related, but not the same thing as mutability. It would help if you explained how they're connected. – wjandrea May 10 '20 at 17:35
  • Better understanding is this if we had list So why there is need of tuple in python you can store heterogeneous data in both of them. So then there is come in different usage of list and tuple in python In dictionary you cannot define list as key because it can be modified and you also know dictionary store key as hash and list cannot be hashed because it can be modified but tuple can be use as key because it is immutable i.e it cannot be change – amanlalwani007 May 10 '20 at 17:40