Reputation: 1184
is there any equivalent to this PHP notation, which changes the original array (be aware of reference operator)?
// increase value of all items by 1
foreach ($array as $k => &$v) {
$v++;
}
I know only this way, which is not so elegant:
for i in range(len(array)):
array[i] += 1
Upvotes: 37
Views: 48802
Reputation: 11315
Regarding references.
In python, every value is object, and every 'variable' is reference to the object. Assignment never copies value, it always assigns reference.
So v in for k,v in enumerate([1,2,3])
is reference too, by default. However most objects of basic 'types' are immutable, therefore when you do immutable_object_reference += 1
you create new instance of int
and change immutable_object_reference
to point to new instance.
When our values are of mutable types, references work same as in PHP:
>>> class mutable_pseudoint(object):
... def __init__(self, d):
... self.d = d
... def __iadd__(self, v):
... self.d += v
... def __repr__(self):
... return self.d.__repr__()
... def __str__(self):
... return self.d.__str__()
...
>>> l = [mutable_pseudoint(1), mutable_pseudoint(2), mutable_pseudoint(3), mutable_pseudoint(4)]
>>> l
[1, 2, 3, 4]
>>> for k,v in enumerate(l):
... v += 1
...
>>> l
[2, 3, 4, 5]
Upvotes: 2
Reputation: 50507
When the built in enumerate()
function is called on a list, it returns an object that can be iterated over, returning a count and the value returned from the list.
for i, val in enumerate(array):
array[i] += 1
Upvotes: 68
Reputation: 11399
You could use list comprehension:
newArray = [i + 1 for i in array]
Upvotes: 5
Reputation: 666
I'm unaware of being able to get a pointer to a list item, but a cleaner way to access by index is demonstrated by http://effbot.org/zone/python-list.htm:
for index, object in enumerate(L):
L[index] = object+1
Upvotes: 1