ActiveState Code

Recipe 106033: Deep list() to convert a nested tuple-of-tuples


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.

Python
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)

Discussion

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.

Comments

  1. 1. At 11:11 a.m. on 18 jun 2009, Daryl Spitzer said:

    I wanted to convert a nested list of tuples or lists, so I made this small modification:

      def deep_list(x):
          """fully copies trees of tuples or lists to a tree of lists.
             deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]
             deep_list( (1,2,[3,(4,5)]) ) returns [1,2,[3,[4,5]]]"""
          if not ( type(x) == type( () ) or type(x) == type( [] ) ):
              return x
          return map(deep_list,x)
    
  2. 2. At 7:01 p.m. on 30 jul 2009, Daryl Spitzer said:

    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:

    def listit(t):
        return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
    

    (It was noted that map() returns a generator in Python 3.x.)

Sign in to comment