Skip to content
Advertisement

Transpose using a map() and lambda

I came across the following code:

JavaScript

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?

Advertisement

Answer

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

JavaScript

l unpacks to:

JavaScript

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:

JavaScript

The mapping function returns a list, so:

JavaScript

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

JavaScript

These individual mappings result in:

JavaScript

Which finally becomes a list:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement