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
Using typing so you can verify data using mypy static analysis tool:
Here we can have
alt_elem
method which can fit in your for loop.Output:
Note: Above solution might not be efficient considering operations performed in func.
While all the answers using
zip
are correct, I find that implementing the functionality yourself leads to more readable code:The
it = iter(it)
part ensures thatit
is actually an iterator, not just an iterable. Ifit
already is an iterator, this line is a no-op.Usage:
Apologies for being late.I hope this will be even more elegant way of doing it.
The title of this question is misleading, you seem to be looking for consecutive pairs, but if you want to iterate over the set of all possible pairs than this will work :