# [Tutor] Group sequence pairwise

Luke Paireepinart rabidpoobear at gmail.com
Sun Feb 25 12:53:41 CET 2007

```Christopher Arndt wrote:
> Given a sequence, how can I group it pairwise, so that I get
>
> [(s0, s1), (s2, s3), ... , (sn-1, sn)]
>
> or, if len(s)%2 != 0
>
> [(s0, s1), (s2, s3), ... , (sn, None)]
>
>
> I have tried to find a solution, using itertools, but I'm not very
> experienced in functional stuff, so I got confused.
Do you mean you're not experienced in using functions or do you mean
you're inexperienced at functional programming?
(If you are not completely sure you know what functional programming is,
that's probably not what you're doing)
I  don't know very much about FP, so I can't tell if this is some common
idiom in that style or not.
> There is a recipe
> ("pairwise") in the itertools docs, that does something similar but not
> quite what I want.
>
Well, this is fairly simple to do with list comprehensions...
>>> x = [1,2,3,4,5,6,7]
>>> if len(x) % 2 != 0: x.append(None)

>>> [(x[a],x[a+1]) for a in range(0,len(x),2)]
[(1, 2), (3, 4), (5, 6), (7, None)]

Dunno if that's what you're after,
also note it modifies the list by adding a None at the end.
That's just the way I chose to do it, but if you need it to not modify
it should be possible as well.
HTH,
-Luke
>

```