Question

How to write a function which needs to access the first value which is not a list from an arbitray-deep nested list? Sometimes right syntax will be somelist[0], some other time somelist[0][0] etc. Is flattening of the whole list just to read the first one correct solution?

Was it helpful?

Solution

I would do something like

value = my_list[0]
if isinstance(value, list):
    value = value[0]

# use the value

OTHER TIPS

This has been answered here.

Summarizing:

from itertools import chain
myList = [ [1, 2, 3], [5, 6], [], [114, 66, 55] ]
flatList = list( chain( *myList ) )

Output: [1, 2, 3, 5, 6, 114, 66, 55]

Then just access flatList[0] for the first element.

Try this:

def get_first_item(value):
    if isinstance(value, list):
        return get_first_item(value[0])
    return value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top