views:

623

answers:

3

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

+4  A: 

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
Christian Rodemeyer
When you need to check an object's type, it's better to use the isinstance() function. As a bonus, you can even check for multiple types at once, like this: isinstance(t, (list, tuple))
efotinis
hasattr(t,'__iter__') perhaps
Jimmy
+5  A: 
def listit(t):
    return list(map(listit, t)) if isinstance(t, (list, tuple)) else t

The shortest solution I can imagine.

aztek
map() always returns a list. list(map( ... )) should be map( ... )
NicDumZ
NicDumZ that's right if you python 2.x but in 3.x map() returns a generator.
DasIch
and what's the difference from Christian's answer?
SilentGhost
A: 

This is what I had come up with, but I like the other's better.

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)

I see aztek's answer can be shortened to:

def deep_list(x):
     return map(deep_list, x) if isinstance(x, (list, tuple)) else x

Update: But now I see from DasIch's comment that this wouldn't work in Python 3.x since map() there returns a generator.

Daryl Spitzer