S.Shafer
S.Shafer

Reputation: 13

multiplying each element in a nested list by 2

The problem is: Define a function called ex_4 that will multiply every element in the inner list by 2. For example:

ex_4([[1, 2, 3], [4, 5], [6, 7, 8]]) ---> [[2, 4, 6], [8, 10], [12, 14, 16]]

Here's what I have.....

def ex_4(LL):
    return list(map(lambda x: x*2, LL[0])), list(map(lambda x: x*2, LL[1])),list(map(lambda x: x*2, LL[2]))

ex_4([[1, 2, 3], [4, 5], [6, 7, 8]])
--> ([2, 4, 6], [8, 10], [12, 14, 16])

This returns the result I'm looking for, however the answer is not returned as a nested list. I'd also like to be able to input additional lists to that, and not have to keep adding LL[3],LL[4], etc.

Upvotes: 1

Views: 1470

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

In that case you can also nest the maps

list(map(lambda L: list(map(lambda x: x*2, L)), LL))

but in this case, it is more elegant here to use nested list comprehension:

[ [ 2*x for x in L ] for L in LL ]

So here the outer list comprehension iterates with L over the elements (sublists) of LL. For every such L, we "yield" the inner list comprehension, where we iterate with x over L and yield 2*x for every element in L.

Upvotes: 4

Related Questions