1

Suppose I create a tuple like so:

>>> a = (1, 2, 3,)

I want to modify it:

>>> a[0] = 10

But this causes an exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Why is it not possible to modify the tuple?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Danielsss
  • 11
  • 1
  • 4
  • Because tuples are immutable. If you want mutable sequences, use lists. – Frédéric Hamidi Apr 01 '14 at 09:30
  • 2
    Does this answer your question? [Python: changing value in a tuple](https://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple) – Georgy Apr 01 '20 at 16:27
  • Tuples can't be changed because they were designed that way. If your question is why they were designed that way (or why Python has both immutable and mutable sequence types), that comes down to efficiency. When you know a sequence can't change, you can allocate exactly the right amount of memory for it (lists use padding, to allow items to be added with constant overhead) and you can store only one copy of a given sequence no matter how many times it is used in the program (called "interning"). – kindall Jan 24 '23 at 15:34

2 Answers2

1

tuples, like strings, are immutable objects in that their values cannot be changed once they have been created. You usually use tuples when you want to store a list of values that you wont be editing, maybe they are constants. If you will be editing, resizing or appending elements to the tuple, use lists instead.

You can do it either as follows:

a = (10, a[1], a[2])

Or using lists. Lists are much more dynamic and allow item assignment and editing.

For example:

>>> a = [1,2,3]
>>> a[0] = 10
>>> a
[10,2,3]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

As you can read here, tuples are immutable sequence types. This means you cannot change them.

Tim
  • 41,901
  • 18
  • 127
  • 145