Reputation: 1919
Consinder the following example:
values = [1,2,3,4,5,6]
Is there a simple way to produce the following output
1 2
3 4
5 6
I tried different methods, for example:
a = [1, 2, 3, 4, 5,6]
for v, w in zip(a[:-1], a[1:]):
print(v, w)
but i always get the same result:
The new line always starts with the last number of the line before
1 2
2 3
3 4
...
Upvotes: 0
Views: 39
Reputation: 20472
How about this:
for i in range(0, len(values), 2):
print(values[i], values[i+1])
Might want to add a check though that i+1
exists, or turn around the logic:
for i in range(1, len(values), 2):
print(values[i-1], values[i])
Upvotes: 1
Reputation: 423
you can do that :
a = [1, 2, 3, 4, 5,6]
for v, w in zip(a[0:-1:2], a[1::2]):
print(v, w)
output
1 2
3 4
5 6
Upvotes: 0
Reputation: 82765
Using slicing with step argument.
Ex:
a = [1, 2, 3, 4, 5,6]
for v, w in zip(a[0::2], a[1::2]):
print(v, w)
Output:
1 2
3 4
5 6
Upvotes: 0