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
...
CodePudding user response:
You can use zip
with a one-off slice:
for i, k in zip(l, l[1:]):
# ...
But in Python >= 3.10 you also have itertools.pairwise
:
from itertools import pairwise
for i, k in pairwise(l):
# ...
This is more space-efficient because it avoids the in-memory list produced by the slice. It can also be used with any iterator/iterable which helps avoid a lot of boilerplate code.
CodePudding user response:
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)]
CodePudding user response:
You can do this with standard indexing:
l = [1,2,3,4,5]
for i in range(1,len(l)):
print( str(l[i-1]), ' ', str(l[i]), '=', str(l[i] l[i-1]) )
Output:
1 2 = 3
2 3 = 5
3 4 = 7
4 5 = 9
CodePudding user response:
You can also do it like this :-
l = [1,2,3,4,5,6]
for i in l:
print (i, ' ', i 1, '=',i i 1)