list() will convert a tuple to a list, but any elements that are also tuples will stay as such. This utility function fully converts an arbitrary "tuple tree" to a same-structured list.
1 2 3 4 5 6 | def deep_list(x):
"""fully copies trees of tuples to a tree of lists.
deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
if type(x)!=type( () ):
return x
return map(deep_list,x)
|
Other datatypes are partially handled by this function. However, if you nest lists within tuples within lists, etc, you might get some elements that are references and not copied.
The copy module has been suggested for this type of problem, but it does not perform the tuple->list part of the transformation.
I wanted to convert a nested list of tuples or lists, so I made this small modification:
Someone on http://stackoverflow.com/questions/1014352/how-do-i-convert-a-nested-tuple-of-tuples-and-lists-to-lists-of-lists-in-python came up with:
(It was noted that map() returns a generator in Python 3.x.)