Skip to content
Advertisement

Changing the value of tuple inside a nested list

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.

Advertisement

Answer

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')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement