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
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
You could use list comprehension:
newArray = [i + 1 for i in array]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With