Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose using a map() and lambda

Tags:

python

I came across the following code:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list(map(lambda *a: list(a), *l)) 

which returns: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I don't quite follow how the values are being transposed. I understand that *l is used to unpack the list, after which I am a little uncertain. Any step by step explanation for this?

like image 956
ANaidu Avatar asked Mar 02 '23 18:03

ANaidu


1 Answers

Here is what that code translates to for the given input:

list(map(lambda *a: list(a), *l)) 

l unpacks to:

list(map(lambda *a: list(a), [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The documentation of map explains what happens when it gets multiple iterable arguments like above:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

So we can continue to break down as follows, knowing that in this case there are 3 iterable arguments, and so the mapping function will get three arguments when it gets called:

list(map(lambda x, y, z: list((x, y, z)), [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The mapping function returns a list, so:

list(map(lambda x, y, z: [x, y, z], [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The mapping function is called for each of the values in the iterable(s) in parallel, so:

list(((lambda x, y, z: [x, y, z])(1, 4, 7), 
      (lambda x, y, z: [x, y, z])(2, 5, 8), 
      (lambda x, y, z: [x, y, z])(3, 6, 9)))

These individual mappings result in:

list(([1, 4, 7], [2, 5, 8], [3, 6, 9]))

Which finally becomes a list:

[ [1, 4, 7], [2, 5, 8], [3, 6, 9] ]
like image 122
trincot Avatar answered Mar 15 '23 17:03

trincot