How do I make a for
loop or a list comprehension so that every iteration gives me two elements?
l = [1,2,3,4,5,6]
for i,k in ???:
print str(i), '+', str(k), '=', str(i+k)
Output:
1+2=3
3+4=7
5+6=11
How do I make a for
loop or a list comprehension so that every iteration gives me two elements?
l = [1,2,3,4,5,6]
for i,k in ???:
print str(i), '+', str(k), '=', str(i+k)
Output:
1+2=3
3+4=7
5+6=11
zip(*iterable)
returns a tuple with the next element of each iterable.l[::2]
returns the 1st, the 3rd, the 5th, etc. element of the list: the first colon indicates that the slice starts at the beginning because there's no number behind it, the second colon is only needed if you want a 'step in the slice' (in this case 2).l[1::2]
does the same thing but starts in the second element of the lists so it returns the 2nd, the 4th, 6th, etc. element of the original list.you can use more_itertools package.
Thought that this is a good place to share my generalization of this for n>2, which is just a sliding window over an iterable:
Well you need tuple of 2 elements, so
Where:
data[0::2]
means create subset collection of elements that(index % 2 == 0)
zip(x,y)
creates a tuple collection from x and y collections same index elements.For anyone it might help, here is a solution to a similar problem but with overlapping pairs (instead of mutually exclusive pairs).
From the Python itertools documentation:
Or, more generally: