Reputation: 453
Given the following example:
container = [ (1, "a") ,
(40, "b") ,
(24, "c") , #we intend to change this
(103, "d")
]
for k,v in container:
if k == 24:
v += " good"
print container
The (24, "c") data pair in container will still remain its original value, and won't be changed to (24, "c good"). What would be the way to alter it to (24, "c good") as intended during the iteration?
I use python 2.7 , but 3.x examples are also welcome.
Thanks.
Upvotes: 1
Views: 409
Reputation: 131
Messed up a bit. Fixed now
container = [ (1, "a") ,
(40, "b") ,
(24, "c") , #we intend to change this
(103, "d")
]
for k, n in enumerate(container):
if n[0] == 24:
container[k] = (n[0], n[1] + " good")
print container
Upvotes: 1
Reputation: 229934
You can use enumerate()
the keep track of the index of the container item you are looking at:
for i, (k,v) in enumerate(container):
if k == 24:
container[i] = (k, v+" good")
Upvotes: 6