Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 749
Stqrosta Avatar asked Sep 05 '25 17:09

Stqrosta


2 Answers

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]]
like image 52
Dani Mesejo Avatar answered Sep 07 '25 07:09

Dani Mesejo


Tuples are immutable. As @ Dani Mesejo suggests, you can use a list.

I suggest converting your list of tuples to a list of lists:

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

# Do the conversion here. 
# Could just start out with a list of lists as well. 
lst = [list(x) for x in lst]

lst[0][1] += 32

print(lst)
# [[0, 32], [1, 1]]

Would make things easier just starting out with a list of lists:

lst = [[0,0], [1,1]]

lst[0][1] += 32

print(lst)
# [[0, 32], [1, 1]]
like image 34
RoadRunner Avatar answered Sep 07 '25 07:09

RoadRunner