I have this code
a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]
I want to change the last name Rob to 'Roberto' if the id = 2
So my idea was to change the tuple to a list so it will be easy to make the change
I tried :
a_len = len(a)
count = 0
a_list = []
while(count < a_len):
a_list.append(a[count])
count ++
for x, element in a_list:
if element[0] == 2:
a_list[x] = Roberto
But this didn't work, do you guys have any idea how to do that?
Thanks!
This does it:
a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]
for i,e in enumerate(a):
if e[0]==2:
temp=list(a[i])
temp[2]='Roberto'
a[i]=tuple(temp)
print a
Prints:
[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]
If you want a list comprehension, this:
>>> [t if t[0]!=2 else (t[0],t[1],'Roberto',t[3],t[4]) for t in a]
[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]
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