-2

I want to retrieve data from n nested lists in Python. That is:

[[[[[1, 2]]]]] => [1, 2]

I could obviously do something like:

mylist[0][0][0][0]

But I'm wondering if there is a way to do this without having to know how deep the nesting of the list is.

I want to do this because I have got some fairly malformed data from a REST API request which needs processing.

BHC
  • 889
  • 1
  • 7
  • 18

1 Answers1

4

You can use a recursive generator to yield elements from nested lists:

from typing import Collection

def check_nested(obj):
    for sub_obj in obj:
        # tuples, lists, dicts, and sets are all Collections
        if isinstance(sub_obj, Collection):
            yield from check_nested(sub_obj)
        else:
            yield sub_obj


l = [[[[[1, 2]]]]]
list(check_nested(l))
[1, 2]

# This will work for other formats
l = [[[[[1, 2]]]], [[3, 4]]]

list(check_nested(l))
[1, 2, 3, 4]

Note about typing.Collection

Because this got a new upvote, I wanted to come back and correct something:

from typing import Collection

isinstance('', Collection)
True

This could result in unintended errors, so a better solution would be an instance check:

def check_nested(obj):
    for sub_obj in obj:
        if isinstance(sub_obj, (list, dict, set, tuple)):
            yield from check_nested(sub_obj)
        else:
            yield sub_obj
C.Nivs
  • 12,353
  • 2
  • 19
  • 44