How do I make a for loop or a list comprehension so that every iteration gives me two elements but the last value must be repeated.
l = [1,2,3,4,5,6]
for i,k in ???:
print str(i), '+', str(k), '=', str(i+k)
Output:
1+2=3
2+3=5
3+4=7
4+5=9
...
>Solution :
You can use zip:
l = [1,2,3,4,5,6]
for i,k in zip(l, l[1:]):
print(f'{i} + {k} = {i+k}')
Output:
1 + 2 = 3
2 + 3 = 5
3 + 4 = 7
4 + 5 = 9
5 + 6 = 11
For more explanation:
>>> list(zip(l, l[1:]))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]