I thought this question was easy enough but couldn't find an answer.
I have a list of tuples of length 2.
I want to get a list of tuples of length 3 in which the third element is the result of some operation over the other two.
Example:
for val_1, val_2 in list_of_tuples
#...
#some multi line operation
#...
val_3 = result
replace (val_1, val_2) by (val_1, val_2, val_3) in list
Any ideas?
Use a list comprehension.
>>> list_of_tups = [(1,2),(2,3),(3,4)]
>>> [(i,j,i+j) for i,j in list_of_tups]
[(1, 2, 3), (2, 3, 5), (3, 4, 7)]
Now re-assign it back
>>> list_of_tups = [(i,j,i+j) for i,j in list_of_tups]
Do not modify lists while iterating as it can have some bad effects.
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