Welcome, guest | Sign In | My Account | Store | Cart

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, 6 lines
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.

2 comments

Daryl Spitzer 14 years, 9 months ago  # | flag

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)
Daryl Spitzer 14 years, 8 months ago  # | flag

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

Created by Drew Perttula on Sun, 6 Jan 2002 (PSF)
Python recipes (4591)
Drew Perttula's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks