1

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.

purga
  • 443
  • 6
  • 20
  • Relevant: http://stackoverflow.com/questions/1637807/modifying-list-while-iterating – Matt Ball Nov 03 '11 at 23:56
  • 1
    v isn't a pointer, and tuples are immutable. The second point is the important one, and the reason all of the correct answers replace the entire tuple and not just the single value. – Scott A Nov 04 '11 at 00:08
  • 2
    If you intend to change the values, you should probably avoid using immutable container (tuple) in the first place. Perhaps a dict would be preferable here. – wim Nov 04 '11 at 00:14

2 Answers2

6

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")
sth
  • 222,467
  • 53
  • 283
  • 367
1

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
Tom Ray
  • 133
  • 3
  • 11
  • That doesn't work because `n` is a tuple and `container[n]` doesn't make sense (In Python's words: "TypeError: list indices must be integers, not tuple") – sth Nov 04 '11 at 00:06
  • You can not index container with n like that. – wim Nov 04 '11 at 00:10
  • Sorry for that, fixed now. Was thinking about dicts when I wrote that. – Tom Ray Nov 04 '11 at 00:10
  • better, but now it identical to sth already provided answer, so you should delete this answer. – wim Nov 04 '11 at 00:11