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
A simple solution.
Closest to the code you wrote:
Output:
I need to divide a list by a number and fixed like this.
Use the
zip
anditer
commands together:which I found in the Python 3 zip documentation:
Which results in:
You need a
pairwise()
(orgrouped()
) implementation.For Python 2:
Or, more generally:
In Python 3, you can replace
izip
with the built-inzip()
function, and drop theimport
.All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.
N.B: This should not be confused with the
pairwise
recipe in Python's ownitertools
documentation, which yieldss -> (s0, s1), (s1, s2), (s2, s3), ...
, as pointed out by @lazyr in the comments.We can also just make the list a set of tuples
output: