views:

918

answers:

4

What is the nicest way of splitting this:

tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')

into this:

tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

Assuming that the input always has an even number of values.

+14  A: 
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]
Peter Hoffmann
+1 more explicit use of the range function
jcoon
+24  A: 

zip() is your friend:

t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
unbeknown
Nice alternative!
jcoon
+1 because it's pretty and I didn't know about the [::] syntax
Steve B.
doesn't works for tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') # note the last 'i', that makes the tuples odd-length
dfa
@dfa: what do you mean it doesn't work? is it specified how new list should be formed in case of odd-length input?
SilentGhost
ops, I've just read: "Assuming that the input always has an even number of values."
dfa
@dfa: well if the input is has an odd number of elements, what should happen to the left over element? Should it be a one element tuple or should it be (x, None)? You have to massage you input according to the expected output.
unbeknown
A: 

Here's a general recipe for any-size chunk, if it might not always be 2:

def chunk(seq, n):
    return [seq[i:i+n] for i in range(0, len(seq), n)]

chunks= chunk(tuples, 2)

Or, if you enjoy iterators:

def iterchunk(iterable, n):
    it= iter(iterable)
    while True:
        chunk= []
        try:
            for i in range(n):
                chunk.append(it.next())
        except StopIteration:
            break
        finally:
            if len(chunk)!=0:
                yield tuple(chunk)
bobince
I think you meant range(0, len(seq), n), rather than range(0, len(seq))
Noah
-1: doesn't work.
nosklo
Noah: ta, indeed.
bobince
+6  A: 

Or, using itertools (see the recipe for grouper):

from itertools import izip
def group2(iterable):
   args = [iter(iterable)] * 2
   return izip(*args)

tuples = [ab for ab in group2(tuple)]
Andrew Jaffe
+1: for mentioning the documentation (you came first:)
ΤΖΩΤΖΙΟΥ