# [Tutor] Group sequence pairwise

David Perlman dperlman at wisc.edu
Sun Feb 25 14:36:07 CET 2007

```I found this by "using Google".  You should be able to make a simple
modification (I can think of a couple of ways to do it) to have it
pad the end with "None".  It is 100% iterator input and output.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279

On Feb 25, 2007, at 7:06 AM, Christopher Arndt wrote:

> Luke Paireepinart schrieb:
>> Christopher Arndt wrote:
>>> 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?
>
> I mean functional programming.
>
>> 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)]
>
> I came a up with a similar solution:
>
> for i in xrange(0, len(s), 2):
>     do_something(s[i])
>     if i+1 <= len(s):
> 	do_something(s[i+1])
>     else:
>         do_something(None)
>
> or
>
> try:
>     for i in xrange(0, len(s), 2):
>         do_something(s[i])
> 	do_something(s[i+1])
> except IndexError:
>     do_something(None)
>     raise StopIteration
>
>> Dunno if that's what you're after,
>
> Not exactly. I wonder if this is possible without modifying the
> original
> sequence (could be not a list too) and I'd also like to find a
> solution
> that generally applies to iterables.
>
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama

```

More information about the Tutor mailing list