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?
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]
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