How do I convert a nested tuple of tuples and lists to lists of lists in Python?
11,127
Solution 1
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
The shortest solution I can imagine.
Solution 2
As a python newbie I would try this
def f(t):
if type(t) == list or type(t) == tuple:
return [f(i) for i in t]
return t
t = (1,2,[3,(4,5)])
f(t)
>>> [1, 2, [3, [4, 5]]]
Or, if you like one liners:
def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
Solution 3
We can (ab)use the fact that json.loads
always produces Python lists for JSON lists, while json.dumps
turns any Python collection into a JSON list:
import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
Author by
Daryl Spitzer
Father of three, husband, computer programmer (Pythonista), skeptic, atheist, podcast listener, baseball fan, Canadian (in the United States).
Updated on June 14, 2022Comments
-
Daryl Spitzer almost 2 years
I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert
(1,2,[3,(4,5)])
to[1,2,[3,[4,5]]]
.How do I do this (in Python)?