Converting a tuple to a list

David Harrison dave.l.harrison at gmail.com
Wed Apr 9 00:34:30 EDT 2008


On 09/04/2008, Gabriel Ibanez <mobile at ibinsa.com> wrote:
> Hi all ..
>
>  I'm trying to using the map function to convert a tuple to a list, without
>  success.
>
>  I would like to have a lonely line that performs the same as loop of the
>  next script:
>
>  -------------------------------------------
>  # Conveting tuple -> list
>
>  tupla = ((1,2), (3,4), (5,6))
>
>  print tupla
>
>  lista = []
>  for a in tupla:
>     for b in a:
>         lista.append(b)
>  print lista
>  -------------------------------------------
>
>  Any idea ?
>
>  Thanks ...
>
>  # Gabriel

Not sure if you were looking for a method that retained the existing
nested structure or not, so the following is a recursive way of
turning an arbitrarily nested tuple structure into the list based
equivalent:

a = ((1,2), (3,4), (5,6), (7,(8,9)))

def t2l(a):
    lst = []
    for item in a:
        if type(item) == tuple:
            lst.append(t2l(item))
        else:
            lst.append(item)
    return lst

print t2l(a)



More information about the Python-list mailing list