Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python converting a tuple (of strings) of unknown length into a list of strings

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.

like image 390
Malcolm Tucker Avatar asked May 12 '15 14:05

Malcolm Tucker


People also ask

How do I turn a tuple into a list in Python?

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.

How do you convert a list of tuples to a list of strings in Python?

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.

How do you convert a tuple to a list of tuples in Python?

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.

How do you convert a string to a list of tuples?

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.


1 Answers

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".

like image 86
Malcolm Tucker Avatar answered Sep 29 '22 09:09

Malcolm Tucker