You do get the desired output using enumerate on the 2-d list m
. You then need to assign the map object back to m
by converting it into a list. You can do it as follows -
APPROACH - 1
m = [[1,2,3],[5,6,7],[9,10,11]]
m=list(map(lambda x: (x[0],x[1]), enumerate(m)))
print(m)
OUTPUT :
[(0, [1, 2, 3]), (1, [5, 6, 7]), (2, [9, 10, 11])]
APPROACH - 2
Another possible way of doing it would be as follows -
m = [[1,2,3],[5,6,7],[9,10,11]]
m=list(map(lambda x: (m.index(x),x), m))
# finding index in m using m.index(x) instead of x.index(x[0]) which would always return 0
print(m)
OUTPUT :
[(0, [1, 2, 3]), (1, [5, 6, 7]), (2, [9, 10, 11])]
What you were trying to do with (x.index(x[0])
finds the element in the elements of your original 2-d list which would always give you 0 (since you are finding the 0th index element in the list which would obviously give 0).
What you should instead be doing is finding the index of element over which you are mapping in the map (and not in x-which is elements of m).
APPROACH - 3 (better alternative than first two versions)
A better solution than the above approaches(as suggested in this answer) is using the list enumeration. So, the solution using list enumeration is as follows -
m = [[1,2,3],[5,6,7],[9,10,11]]
m=[(index,element) for index,element in enumerate(m)]
print(m)
OUTPUT :
[(0, [1, 2, 3]), (1, [5, 6, 7]), (2, [9, 10, 11])]
This approach turns out to be somewhat faster than using the map with lambda approach. You can read more about list enumeration here
APPROACH - 4 (one-liner)
Since enumerate()
returns an enumerate object which contains index and the element itself, the approach-3 could be modified to a shorter and simpler version as follows -
m = [[1,2,3],[5,6,7],[9,10,11]]
print(list(enumerate(m)))
OUTPUT :
[(0, [1, 2, 3]), (1, [5, 6, 7]), (2, [9, 10, 11])]