[Tutor] how to convert array into tuple

bhaaluu bhaaluu at gmail.com
Thu Sep 27 21:50:59 CEST 2007


Can you explain how this works? How would this be written in
a "conventional" way?

>>> foo = [1,2,3,4,5,6]
>>> [(foo[i],foo[i+1]) for i in range(0,len(foo),2)]
[(1, 2), (3, 4), (5, 6)]
>>> foo = [1,2,3,4,5,6,7,8,9]
>>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-4,2)]
[(1, 2), (3, 4), (5, 6)]

Also, what kinds of ways might this be used?
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

On 9/27/07, Kent Johnson <kent37 at tds.net> wrote:
> Noufal Ibrahim wrote:
>
> > This seems to work although I'd like comments from the more experienced
> > Pythonistas out there.
> >
> >  >>> foo
> > [1, 2, 3, 4, 5, 6, 7, 8, 9]
> >  >>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-2,2)]
> > [(1, 2), (3, 4), (5, 6), (7, 8)]
>
> This problem is a perennial favorite on comp.lang.python and in the
> cookbook, which I take to mean that there is no clear best solution. You
> can see some alternatives here
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044
>
> and in the links at the bottom of that page.
>
> One question is what to do with partial groups at the end; your version
> truncates the original list.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list