Search code examples
pythonnested-lists

Get element from list of list based on index from another list


I would like to retrieve specific elements within a list of lists without using list comprehension, loops, or any iterative approach in Python.

For example, given this list:

[[1,2,3,4],[3,4],[5,6,7]]

and this vector:

[0,0,1]

I would like to retrieve the 0th element on the 0th list, the 0th element of the 1st list, and the 1st element of the 2nd list:

[1,2,3,4][0] -> 1
[3,4][0] -> 3
[5,6,7][1] -> 6

Which should give this result:

[1,3,6]

Is this possible in python?


Solution

  • Using a list comprehension with zip() is one of the most Pythonic way to achieve this:

    >>> my_list = [[1,2,3,4],[3,4],[5,6,7]]
    >>> my_vector = [0,0,1]
    
    >>> [x[i] for x, i in zip(my_list, my_vector)]
    [1, 3, 6]
    

    However, since OP can not use list comprehension, here's an alternative using map() with lambda expression as:

    >>> list(map(lambda x, y: x[y], my_list, my_vector))
    [1, 3, 6]
    

    In the above solution, I am explicitly type-casting the object returned by map() to list as they return the iterator. If you are fine with using iterator, there's no need to type-cast.