I have a recursive tuple of strings that looks like this:
('text', ('othertext', ('moretext', ('yetmoretext'))))
(it's actually a tuple of tuples of strings - it's constructed recursively)
And I'd like to flatten it into a list of strings, whereby foo[1] would contain "text", foo[2] "othertext" and so forth.
How do I do this in Python?
The duplicate is about a 2D list of lists, but here I'm dealing with a recursive tuple.
We can use the list() function to convert tuple to list in Python. After writing the above code, Ones you will print ” my_tuple ” then the output will appear as a “ [10, 20, 30, 40, 50] ”. Here, the list() function will convert the tuple to the list.
Method #1 : Using list comprehension + join() The list comprehension performs the task of iterating the entire list of tuples and join function performs the task of aggregating the elements of tuple into a one list.
To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
I've found the answer myself, I'll provide it here for future reference:
stringvar = []
while type(tuplevar) is tuple:
stringvar.append(tuplevar[0])
tuplevar=tuplevar[1]
stringvar.append(tuplevar) # to get the last element.
Might not be the cleanest/shortest/most elegant solution, but it works and it seems quite "Pythonic".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With