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.
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]]
Tuples, as Dani points out in his comment, are immutable.
You should create a new tuple and swap the tuple like this:
lst[0] = (lst[0][0], lst[0][1] + 32)
lst
Maybe something like this?
x, y = 0, 0
x2, y2 = 1, 1
lst = [(x, y), (x2, y2)]
lst[0] = (lst[0][0], lst[0][1] + 32)
>> [(0, 32), (1, 1)]
as per w3schools https://www.w3schools.com/python/python_tuples.asp
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = (1, 2, 3)
y = (4, 5, 6)
x1 = list(x)
y2 = list(y)
z = [x1, y2]
z[0][1] += 32
x = tuple(z[0])
y = tuple(z[1])
print(z) returns:
[[1, 32, 3], [4, 5, 6]]
print(x) returns:
(1, 34, 3)
print(y) returns:
(4, 5, 6)