Reputation:
How do I change the second value of the first tuple in the first list by force??
test_list=[[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
Please help! Thanks in advance.
Upvotes: 0
Views: 714
Reputation: 4427
Tuples are immutable. You would need to replace it instead.
Since lists are mutable, you would replace the first element of the first list with a new tuple having a changed second value.
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# test_list - unchanged
# test_list[0] - modified
# test_list[0][0] - replaced
# test_list[0][0][0] - preserved
# test_list[0][0]1] - new
new_second_value = 'foobar'
new_value = (test_list[0][0][0], new_second_value)
test_list[0][0] = new_value
This would give you:
>>> test_list
[[(12, 'foobar'), (13, 6)], [(12, 2), (13, 2)]]
To do it in one line:
test_list[0][0] = (test_list[0][0][0], 'foobar')
Note that if you were using named tuples, you could simplify this slightly with a ._replace()
method (https://docs.python.org/2/library/collections.html#collections.somenamedtuple._replace):
test_list[0][0] = test_list[0][0]._replace(foo='bar')
Upvotes: 0
Reputation: 1142
Tuples are immutable. You can not change the value of tuple. To update the value you need to create a new tuple with updated value and then you can replace in the array. Tuples in python
Upvotes: 1