Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map on every other list item Python

Lets say I want to multiply every other integer in a list by 2.

list = [1,2,3,4]
double = lambda x: x * 2
print map(double, list[::2])

I get returned the slice of every other item.

What if I want to destructively change every other item in a list so I get returned the list [1, 4, 3, 8] instead?

like image 980
Lasonic Avatar asked Dec 15 '22 15:12

Lasonic


1 Answers

You can assign to a slice:

>>> list_ = [1,2,3,4]
>>> double = (2).__mul__
>>> map(double, list_[1::2])
[4, 8]
>>> list_[1::2] = map(double, list_[1::2])
>>> list_
[1, 4, 3, 8]
like image 195
wim Avatar answered Dec 17 '22 05:12

wim