Saaraj Saaraj - 3 years ago 159
Python Question

replacing an element of a tuple by another element stored in a list in python

I have a list:

replace_by=['a1','b1','c1','d1','e1']


I also have a list of tuples in the type of

main_list=[('a',[]),('b',[]),('c',[]),('d',[]),('e',[])]


My main goal is to replace the first elements of each tuple in the main_list namely a,b,c,d,e by the corresponding elements in the replace_by list namely a1,b1,c1,d1,e1.

I would appreciate if any one could help me with this in a pythonic way! Thanks in advance!!

Answer Source

Tuples cannot be modified in place. However you can easily create a new version,

replace_by=['a1','b1','c1','d1','e1']
main_list=[('a',[]),('b',[]),('c',[]),('d',[]),('e',[])]

new_list = [(replace_by[i],b)for (i,(a,b)) in enumerate(main_list)]
print(new_list)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download