[Tutor] how to convert array into tuple
Noufal Ibrahim
noufal at airtelbroadband.in
Fri Sep 28 19:35:52 CEST 2007
bhaaluu wrote:
> Can you explain how this works? How would this be written in
> a "conventional" way?
I'm not sure if this is addressed to me but I'll reply anyway. :)
>>>> foo = [1,2,3,4,5,6]
>>>> [(foo[i],foo[i+1]) for i in range(0,len(foo),2)]
range(0,len(foo)) would create a list of consecutive numbers starting
from the first argument (0) till (but not including) the last (len(foo))
This will run as range(0,6) and will return
[0,1,2,3,4,5]
The 2 as the third argument to range specifies the increment (common
difference of the arithmetic progression). So if you say range(0,10,2),
you'd get [0,2,4,6,8]. If you say range(0,10,3), you'd get [0,3,6,9]
etc. Thus the list comprehension is written to iterate over [0,2,4]
i is used as the loop variable in the list comprehension and we return
tuples consisting of the ith and the i+1th elements of the list.
So, it should return
[(foo[0],foo[1]),
(foo[2],foo[3]),
(foo[4],foo[5])
]
Which is the result. Using a for loop, you can write this as
res = []
for i in range(0,len(foo),2):
res.append( (foo[i],foo[i+1],))
print res
I hope I'm clear
> Also, what kinds of ways might this be used?
I can't off the cuff think of anything.
Peace
--
~noufal
More information about the Tutor
mailing list