James
James

Reputation: 538

Compare two adjacent elements in same list

I have already gone through a post but I want to know what I did wrong in my code while using for loop.

List a given as:

a = [2, 4, 7,1,9, 33]

All I want to compare two adjacent elements as :

2 4
4 7
7 1
1 9
9 33

I did something like:

for x in a:
    for y in a[1:]:
        print (x,y)

Upvotes: 7

Views: 12284

Answers (2)

jpp
jpp

Reputation: 164623

Your outer loop persists for each value in your inner loop. To compare adjacent elements, you can zip a list with a shifted version of itself. The shifting can be achieved through list slicing:

for x, y in zip(a, a[1:]):
    print(x, y)

In the general case, where your input is any iterable rather than a list (or another iterable which supports indexing), you can use the itertools pairwise recipe, also available in the more_itertools library:

from more_itertools import pairwise

for x, y in pairwise(a):
    print(x, y)

Upvotes: 11

sophros
sophros

Reputation: 16640

You are comparing a stable element with all of the elements in the list but the first.

The correct way would be:

for i in range(len(a)-1):
    x = a[i]
    y = a[i+1]
    print (x,y)

Upvotes: 5

Related Questions