Converting a tuple to a list

John Krukoff jkrukoff at ltgc.com
Tue Apr 8 19:14:07 EDT 2008


On Wed, 2008-04-09 at 00:46 +0200, Gabriel Ibanez wrote:
> Gabriel Ibanez 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
> >
> 
> list(tupla)
> 
> would probably do it.
> 
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> 
> That would just make a list of tuples, I think he wants [1, 2, 3, 4, 5, 6].
> 
> Try:  l = [x for z in t for x in z]
> 
> --Brian
> 
> 
> ---------------
> 
> 
> Thanks Steve and Brian,
> 
> Brian: that is !!
> 
> However, it's a bit difficult to understand now. I have read it several 
> times :)
> 
> 

Another solution using the itertools module:

>>> import itertools
>>> t = ( ( 1, 2 ), ( 3, 4 ), ( 5, 6 ) )
>>> list( itertools.chain( *t ) )
[1, 2, 3, 4, 5, 6]

Though the list part is probably unnecessary for most uses. The problem
gets interesting when you want to recursively flatten an iterable of
arbitratrily deeply nested iterables.

-- 
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company




More information about the Python-list mailing list