Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Perform an operation on an element of a tuple

Tags:

python

I have a tuple (x,y) where x is a string and y is an integer. Now I want to perform an operation on y, like y += 1, without wanting to create a new tuple. How can I do that?

like image 629
uitty400 Avatar asked Dec 06 '25 04:12

uitty400


2 Answers

Tuples are immutable, so you can't directly modify the variable

>>> t = ('foobar', 7)
>>> t[1] += 1
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    t[1] += 1
TypeError: 'tuple' object does not support item assignment

So you'd have to assign back a new tuple

>>> t = (t[0], t[1]+1)
>>> t
('foobar', 8)
like image 97
Cory Kramer Avatar answered Dec 07 '25 20:12

Cory Kramer


You can't - tuples are immutable. Any attempt of changing an existing tuple would result in TypeError: 'tuple' object does not support item assignment.

What can be done is re-binding object name to a new tuple based on the previous one.

t = ('a', 1)
t = (t[0], t[1]+1)
assert t == ('a', 2)
like image 44
Łukasz Rogalski Avatar answered Dec 07 '25 20:12

Łukasz Rogalski