Converting a tuple to a list

CM cmpython at gmail.com
Wed Apr 9 00:18:56 EDT 2008


On Apr 8, 6:46 pm, "Gabriel Ibanez" <mob... at ibinsa.com> 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 :)

Doing it this way is called a "list comprehension", which means you
put the formula inside the brackets and that new list will be built
with the formula.  This one is also easier to understand if you
substitute more meaningful names than l, x,t,z...like so:

newlist = [number for subtuple in fulltuple for number in subtuple]

or, writing it in the typical for loop way (not using the list
comprehension shortcut):

for subtuple in fulltuple:
    for number in subtuple:
        newlist.append(number)

but the list comprehension doesn't need the append part, it is built
in.  They're handy.



More information about the Python-list mailing list