How to add (not append) a number to an existing value in a tuple?

Stqrosta :

How could I do something like this without getting an error:

x,y = 0,0
x2,y2 = 1,1
lst = [(x,y), (x2,y2)]
lst[0][1] += 32

When I do that I get a TypeError, and the try method doesn't do what I want to do.

Dani Mesejo :

As specify in the documentation on tuples:

Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking

So you could do the following:

Approach 1: Create a new Tuple

x, y = 0, 0
x2, y2 = 1, 1
lst = [(x, y), (x2, y2)]
lst[0] = (lst[0][0], lst[0][1] + 32)

print(lst)

Output

[(0, 32), (1, 1)]

Approach 2: use list

x, y = 0, 0
x2, y2 = 1, 1
lst = [[x, y], [x2, y2]]
lst[0][1] +=  32

print(lst)

Output

[[0, 32], [1, 1]]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379310&siteId=1