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

前端 未结 3 545
孤独总比滥情好
孤独总比滥情好 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:40

    Here ya go:

    # Your for loop should be rewritten as follows:
    for index in xrange(len(a)):
        a[index] += 1
    

    Incidentally, item IS a reference to the item in a, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine:

    >>> a = [[1], [2], [3], [4]]
    >>> for item in a: item += [1]
    >>> a
    [[1,1], [2,1], [3,1], [4,1]]
    

提交回复
热议问题