Heißenberg93
Heißenberg93

Reputation: 1919

How do I iterate through through specific pairs of a list - Python

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

Answers (3)

FlyingTeller
FlyingTeller

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

Alexall
Alexall

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

Rakesh
Rakesh

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

Related Questions