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