0

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

Let us have a list, there is always an even number of elements. We must break it down by pairing. Example: list['1','2','3','4'] need 1,2 and 3,4

Community
  • 1
  • 1
Denis
  • 7,127
  • 8
  • 37
  • 58

4 Answers4

3
>>> L = [1, 2, 3, 4]
>>> pairs = zip(L[::2], L[1::2])
>>> print pairs
[(1, 2), (3, 4)]

Hope this helps

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

If you want two halfs of a list.

l = [1,2,3,4]
print l[:len(l)/2], l[len(l)/2:]
>>> [1, 2] [3, 4]

If you want split a list by pairs then your question is exact duplicate.

Community
  • 1
  • 1
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
0

You can use something like this too:

lVals = xrange(1,101)
size = len(lVals)
output = ((lVals[i], lVals[i+1] if size > i+1 else None) for i in xrange(0, size, 2))
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
0

Adapted from: How do you split a list into evenly sized chunks?

from itertools import izip_longest
data = range(6)
data_iters = [iter(data)] * 2
pairs = izip_longest(*data_iters)
[pair for pair in pairs]
>>> [(0, 1), (2, 3), (4, 5)]

The clever part is that the two elements of data_iters refer to the same object. Izip_longest alternately consumes from the two iterators passed as arguments, but since they're referring to the same object, it effectively pairs the elements in the iterator.

I take no credit for being clever here, upvote the comment I linked to if you liked my answer. :)

Community
  • 1
  • 1