Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of php's foreach($array as $key => &$value)

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  
like image 803
Daniel Milde Avatar asked May 01 '11 22:05

Daniel Milde


2 Answers

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 
like image 124
Acorn Avatar answered Oct 05 '22 23:10

Acorn


You could use list comprehension:

newArray = [i + 1 for i in array] 
like image 20
Sahas Avatar answered Oct 06 '22 01:10

Sahas