Use list of nested indices to access list element

Related searches

How can a list of indices (called "indlst"), such as [[1,0], [3,1,2]] which corresponds to elements [1][0] and [3][1][2] of a given list (called "lst"), be used to access their respective elements? For example, given

    indlst = [[1,0], [3,1,2]]
    lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
    (required output) = [lst[1][0],lst[3][1][2]]

The output should correspond to ["b","h"]. I have no idea where to start, let alone find an efficient way to do it (as I don't think parsing strings is the most pythonic way to go about it).

EDIT: I should mention that the nested level of the indices is variable, so while [1,0] has two elements in it, [3,1,2] has three, and so forth. (examples changed accordingly).

You can just iterate through and collect the value.

>>> for i,j in indlst:
...     print(lst[i][j])
... 
b
f

Or, you can use a simple list comprehension to form a list from those values.

>>> [lst[i][j] for i,j in indlst]
['b', 'f']

Edit:

For variable length, you can do the following:

>>> for i in indlst:
...     temp = lst
...     for j in i:
...         temp = temp[j]
...     print(temp)
... 
b
h

You can form a list with functions.reduce and list comprehension.

>>> from functools import reduce
>>> [reduce(lambda temp, x: temp[x], i,lst) for i in indlst]
['b', 'h']

N.B. this is a python3 solution. For python2, you can just ignore the import statement.

Python Nested List, Access Nested List Items by Index. You can access individual items in a nested list using multiple� You can access individual items in a nested list using multiple indexes. The indexes for the items in a nested list are illustrated as below: L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h'] print(L) # Prints ['cc', 'dd', ['eee', 'fff']] print(L) # Prints ['eee', 'fff'] print(L) # Prints eee

you can try this code block:

required_output = []
for i,j in indlst:
    required_output.append(lst[i][j])

11. Lists — How to Think Like a Computer Scientist: Learning with , If you are going to use an integer index to access the list, it is a good idea to use a list can contain another list, the nested list still counts as a single element in� List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Recursion can grab arbitrary/deeply indexed items from nested lists:

indlst = [[1,0], [3,1,2]]
lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
#(required output) = [lst[1][0],lst[3][1][2]]


def nested_lookup(nlst, idexs):
    if len(idexs) == 1:
        return nlst[idexs[0]]
    return nested_lookup(nlst[idexs[0]], idexs[1::])

reqout = [nested_lookup(lst, i) for i in indlst]
print(reqout) 

dindx = [[2], [3, 0], [0], [2], [3, 1, 2], [3, 0], [0], [2]]    
reqout = [nested_lookup(lst, i) for i in dindx]
print(reqout)
['b', 'h']
['d', 'e', 'a', 'd', 'h', 'e', 'a', 'd']  

I also found that arbitrary extra zero indices are fine:

    lst[1][0][0]
    Out[36]: 'b'

    lst[3][1][2]
    Out[37]: 'h'

    lst[3][1][2][0][0]
    Out[38]: 'h'

So if you actually know the max nesting depth you can fill in the index list values by overwriting your (variable number, shorter) index list values into the max fixed length dictionary primed with zeros using the .update() dictonary method Then directly hard code the indices of nested list, which ignores any "extra" hard coded zero valued indices

below hard coded 4 depth:

def fix_depth_nested_lookup(nlst, idexs):
    reqout = []
    for i in idexs:
        ind = dict.fromkeys(range(4), 0)
        ind.update(dict(enumerate(i)))
        reqout.append(nlst[ind[0]][ind[1]][ind[2]][ind[3]])
    return reqout

print(fix_depth_nested_lookup(lst, indlst))
['b', 'h']

10.23. Nested Lists — How to Think like a Computer Scientist , In this list, the element with index 3 is a nested list. It is also possible to combine those steps using bracket operators that evaluate from left to right. Run Python List index () The index () method returns the index of the specified element in the list. The syntax of the list index () method is: list.index (element, start, end)

Python List (With Examples), Nested lists are list objects where the elements in the lists can be lists themselves . we can access the first element in table , which is nothing but the Cdegrees list, Using this figure, you can realize that the first index looks up an element in � Total Number of elements : 14. Use List comprehension to count elements in list of lists. Iterate over the list of lists using List comprehension. Build a new list of sizes of internal lists. Then pass the list to sum() to get total number of elements in list of lists i.e.

Nested lists, Hope, you like this post of how to get list element by index using Python. If you have any query regarding the tutorial, please comment below. References. Promiz Tutorial on Python List index() Stackoverflow Discussion to Find List index in Python; Also tell me, which method you are using to access list items by index and slice using Python.

Since each item of grades is a list, It can also be indexed. So, the list at index zero gives a two element list with string assignment one and grade 80, and we can use a second index to access each part. So, at grades at index zero and index zero is assignment one, and grades at index zero and index one is 80. Similarly, for the element of

Comments
  • I think the output will be ['b','f']
  • You have a list and you have indices, just reference elements of your list using these indices.
  • @Iron The difficult part comes from not knowing beforehand how many indices there will be to reference a single given element. So instead of being able to reference an element with i and j as would be typical, I don't know how many variables will be necessary.