Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating tuple values in python

Tags:

python

We can not update or modify tuple in python.
I am writting a code that is updating a tuple.

Why is it not giving any error? Here is my code

tuple1=(1,'hello',5,7,8,)
tuple1=tuple1[1:3]*2
print tuple1
print tupele1[3]

Why is it showing the output without any error?

Output :('hello', 5, 'hello', 5)

5

like image 679
user2553017 Avatar asked Mar 19 '26 02:03

user2553017


2 Answers

You're not updating the tuple, you're creating a new tuple with different values.

like image 160
BrenBarn Avatar answered Mar 26 '26 14:03

BrenBarn


You aren't mutating the tuple, you're rebinding the name bound to it. This is not restricted by Python.

>>> (1, 2, 3)[1] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a = (1, 2, 3)
>>> a = 4
like image 33
Ignacio Vazquez-Abrams Avatar answered Mar 26 '26 14:03

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!