0

I need to make tuple of list with 2 items.

For example if I have list range(10)

I need to make tuple like this:

[(0,1),(2,3),(4,5),(6,7),(8,9)]

How can I implement that?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Pol
  • 24,517
  • 28
  • 74
  • 95
  • possible duplicate of [Multiple Tuple to Two-Pair Tuple in Python?](http://stackoverflow.com/questions/756550/multiple-tuple-to-two-pair-tuple-in-python) – Fred Larson Jul 30 '10 at 20:09
  • duplicate: http://stackoverflow.com/questions/870652/pythonic-way-to-split-comma-separated-numbers-into-pairs/870677#870677 – FogleBird Jul 30 '10 at 20:33
  • possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – tzot Feb 27 '11 at 22:11

3 Answers3

3

Many different ways. Just to show off a few:

As list comprehension, where l is a sequence (i.e. integer indexes): [(l[i], l[i+1]) for i in range(0,len(l),2)]

As generator function, works for all iterables:

def some_meaningful_name(it):
    it = iter(it)
    while True:
        yield next(it), next(it)

Naive via list slicing (sucksy performance for larger lists) and copying, again using list comprehension: [pair for pair in zip(l[::2],l[1::2])].

I like the second best, and it's propably the most pythonic and generic (and since it's a generator, it runs in constant space).

2

See the grouper recipe from the itertools docs:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    """
    >>> grouper(3, 'ABCDEFG', 'x')
    ["ABC", "DEF", "Gxx"]
    """
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

This means that you can do:

[(el[0], el[1]) for el in grouper(2, range(10))]

Or more generally:

[(el[0], el[1]) for el in grouper(2, elements)]
Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
0

Can also be done with numpy:

import numpy
elements = range(10)

elements = [tuple(e) for e in numpy.array(elements).reshape(-1,2).tolist()]
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
beitar
  • 156
  • 4