If you are happy that the recursion level will not become terrible (and you are using an updated version of Python):
def unpack(obj): for x in obj: if isinstance(x, str): yield x elif isinstance(x, tuple): yield from unpack(x) else: raise TypeError x = ('text', ('othertext', ('moretext', ('yetmoretext',)))) result = list(unpack(x)) print(result)
You'll get:
['text', 'othertext', 'moretext', 'yetmoretext']
This will also work if there is more than 1 row before the next tuple, or if there are tuples directly in the tuples or rows after the tuples, etc. You can also easily change it to work with other types, if you need, I probably was too wrong on the side of caution.
source share