If you want to print individually the elements of a simple irregular sequence, a sequence formed of regular sequences, one option is to flatten this sequence to print individually the elements in the way that suits you.
To flatten a single irregular sequence, the class method can be used chain.from_iterable()
which is used to chain the elements of an eternal consisting of eternal.
As argument is passed to chain.from_iterable()
a list comprehension that traverses a sequence checking whether each element also a sequence. If the element is a sequence just copy it, or convert it to tuple itself resulting in a list of sequences:
from itertools import chain
from collections.abc import Sequence
lista = [1,2,3,4,5,[6,7,8,9],10,11,12,13,14,15]
l = chain.from_iterable([e if isinstance(e, Sequence) else (e,) for e in lista])
print(*l, sep="\n")
In the case of a composite irregular sequence, a sequence formed of regular and irregular sequences, a recursive algorithm similar to the previous one is used that when it comes across a previously nested sequence it flattens:
from itertools import chain
from collections.abc import Sequence
lista = [1,[(2,[[[3]]])],4,5,[[6,7,[8,9]]],10,11,[[[12]]],(13,14,15)]
def achatar(l):
return chain.from_iterable([achatar(e) if isinstance(e, Sequence) else (e,) for e in l])
l= achatar(lista)
print(*l, sep="\n")
Algorithm that can converted to a lambda expression:
from itertools import chain
from collections.abc import Sequence
lista = [1,[(2,[[[3]]])],4,5,[[6,7,[8,9]]],10,11,[[[12]]],(13,14,15)]
(achatar:= lambda l: chain.from_iterable([achatar(e) if isinstance(e, Sequence) else (e,) for e in l]))
l= achatar(lista)
print(*l, sep="\n")
Test the algorithms in Repl.it