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.
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With