Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify each element in a list

Tags:

python

list

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?

like image 490
José Avatar asked Dec 03 '22 16:12

José


1 Answers

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.

like image 94
Bhargav Rao Avatar answered Dec 05 '22 05:12

Bhargav Rao