Using a map in every other Python list item

Suppose I want to multiply every other integer in the list by 2.

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

I get a slice of every other item.

What if I want to destroy every other element in the list to get a list instead [1, 4, 3, 8]?

+4
source share
3 answers

You can assign 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]
+6
source

Do you really want to do this in a functional way? It can be much easier to read:

for i in range(1, len(l), 2):
    l[i] = l[i] * 2

or you can use a simple list comprehension and assign a slice:

l[1::2] = [x * 2 for x in l[1::2]]

or

l = [x * (2 if i % 2 == 1 else 1) for i, x in enumerate(l)]
+3
source

you can change the definition for lambda

lst = [1,2,3,4]
double = lambda l: [l[x]*2 if x%2!=0 else l[x] for x in range(len(l))]
print lambda(lst)
+1
source

All Articles