Can someone explain how this code snippet works, i know it finds the transpose of a list of lists but I am having a tough time finding how

StackOverflow https://stackoverflow.com/questions/5019927

Question

def transposed(lists):
   if not lists: return []
   return map(lambda *row: list(row), *lists)
Was it helpful?

Solution

Let's assume

list1 = [0, 1, 2]
list2 = [3, 4, 5]
list3 = [6, 7, 8]
lists = [list1, list2, list3]

Then the call

map(lambda *row: list(row), *lists)

is equivalent to

map(lambda *row: list(row), list1, list2, list3)

From the documentation of map(), we can see it applies the given lambda function to the elements of the list in the following way:

f = lambda *row: list(row)
return [f(list1[0], list2[0], list3[0]),
        f(list1[1], list2[1], list3[1]),
        f(list1[2], list2[2], list3[2])]

The lambda function in turn just tranforms its argument list into a Python list object, so we end up with

return [[list1[0], list2[0], list3[0]],
        [list1[1], list2[1], list3[1]],
        [list1[2], list2[2], list3[2]]]

which is the original lists transposed.

OTHER TIPS

Calling map with a function f and several iterables a, b, c, ... returns [f(a[0], b[0], c[0]), f(a[1], b[1, c[1], ...]) (so it essentially zips the lists and unpacks the resulting tuples for each function call). In this case, f takes a variable number of arguments (*row, which will be a tuple containing all (sequential) arguments) and joins them into a list. So it turns [[a[0], a[1], ...], [b[0], ...], ...] into [[a[0], b[0], ...], [a[1], ...], ...] - what we want.

You can use Use [list(row) for row in itertools.izip_longest(*lists)] as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top