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
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
>>> L = [1, 2, 3, 4]
>>> pairs = zip(L[::2], L[1::2])
>>> print pairs
[(1, 2), (3, 4)]
Hope this helps
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.
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))
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. :)