How do I operate on the actual object, not a copy, in a python for loop?

前端 未结 3 553
孤独总比滥情好
孤独总比滥情好 2021-01-04 13:13

let\'s say I have a list

a = [1,2,3]

I\'d like to increment every item of that list in place. I want to do something as syntactically easy

3条回答
  •  佛祖请我去吃肉
    2021-01-04 13:46

    In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.

    What's happening is that in the line: item += 1 you are creating a new integer (with a value of item + 1) and binding the name item to it.

    What you want to do, is change the integer that a[index] points to which is why the line a[index] += 1 works. You're still creating a new integer, but then you're updating the list to point to it.

    As a side note:

    for index,item  in enumerate(a):
        a[index] = item + 1
    

    ... is slightly more idiomatic than the answer posted by Triptych.

提交回复
热议问题