How can I control the actual object, not the copy, in a python loop?

let's say i have a list

a = [1,2,3]

I would like to increase each item in this list. I want to do something syntactically simple, like

for item in a:
    item += 1

but in this example python uses only the value item, not its actual reference, so when I finished with this loop ait still returns [1,2,3] instead of [2,3,4]. I know I can do something like

a = map(lambda x:x+1, a)

but this really is not suitable for my current code, and I would not want to rewrite it: - \

+5
source share
3 answers

Here ya go:

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

, IS item a, , , . :

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

python ( , , ) , ( ), .

: item += 1 ( item + 1) item.

, , a[index] , a[index] += 1. , , .

:

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

... , , Triptych.

+12

map,

a = [item + 1 for item in a]
+9

All Articles