iterator question

johnzenger at gmail.com johnzenger at gmail.com
Tue Sep 26 19:21:12 CEST 2006


def transform(seq, size):
    i = 0
    while i < len(seq):
        yield tuple(seq[i:i+size])
        i += size

Neal Becker wrote:
> Any suggestions for transforming the sequence:
>
> [1, 2, 3, 4...]
> Where 1,2,3.. are it the ith item in an arbitrary sequence
>
> into a succession of tuples:
>
> [(1, 2), (3, 4)...]
>
> In other words, given a seq and an integer that specifies the size of tuple
> to return, then for example:
>
> seq = [a,b,c,d,e,f]
> for e in transform (seq, 2):
>   print e
> 
> would return
> (a,b)
> (c,d)
> (e,f)




More information about the Python-list mailing list