I have a 2D list and want to change one of the values inside of it
I have tried converting to a list and back again. But i do not think that is what I am looking for.
a = [(3, 12, .05), (6, 1, .3)]
a[0][2] = 543
I have a 2D list and want to change one of the values inside of it
I have tried converting to a list and back again. But i do not think that is what I am looking for.
a = [(3, 12, .05), (6, 1, .3)]
a[0][2] = 543
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.
a = [(3, 12, .05), (6, 1, .3)]
y = list(a[0])
y[2] = 543
a[0] = tuple(y)
print a
As @ShantesharInde said, tuples are unchangeable/immutable. They are declared by parentheses (). Lists are created by brackets []. So in your code a is a list of tuples. Two ways to make it changeable/mutable.
Method 1: Change declaration
>>> a = [[3, 12, .05], [6, 1, .3]]
>>> a[0][2] = 543
>>> a
[[3, 12, 543], [6, 1, 0.3]]
Method 2: convert inner tuples to lists
>>> a = [(3, 12, .05), (6, 1, .3)]
>>> for idx, item in enumerate(a):
... a[idx] = list(item)
...
>>> a[0][2] = 543
>>> a
[[3, 12, 543], [6, 1, 0.3]]
The for loop with enumerate is a nice way of doing things if your list has many entries. For just two elements, you could just do
a[0] = list(a[0])
a[1] = list(a[1])
If you're wondering why converting to list didn't work for you before, it's because the list() function will only try to convert the outermost elements. So converting a list to a list has no effect.