Kevin
Kevin

Reputation: 1085

How to map a function to every item in every sublist of a list

Is there a way to do this without using a regular for loop to iterate through the main list?

>>> map(lambda x: x*2, [[1,2,3],[4,5,6]])
[[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]
# want [[2,4,6],[8,10,12]]

Upvotes: 3

Views: 513

Answers (3)

miradulo
miradulo

Reputation: 29690

This is a bit overkill and not too practical for this particular example, but another stylistic option could be to use functools.partial to make it very clear what is happening and a combination of map and a list comprehension.

from functools import partial
from operator import mul

l = [[1, 2, 3], [4, 5, 6]]

double = partial(mul, 2)
dub_l = [map(double, sub) for sub in l]

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Alternative solution would be to go for numpy vectorized operations:

import numpy as np

ll = [[1,2,3],[4,5,6]]

(2*np.array(ll)).tolist()
#Out[6]: [[2, 4, 6], [8, 10, 12]]

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239463

You have nested lists, and x represents just one of the lists. To process that, you need to actually map the multiplication function on to the individual elements of x, like this

>>> map(lambda x: map(lambda y: y * 2, x), [[1, 2, 3], [4, 5, 6]])
[[2, 4, 6], [8, 10, 12]]

But I would prefer list comprehension over this,

>>> [[y * 2 for y in x] for x in [[1, 2, 3], [4, 5, 6]]]
[[2, 4, 6], [8, 10, 12]]

Upvotes: 11

Related Questions