6

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)
jpp
  • 159,742
  • 34
  • 281
  • 339
James
  • 528
  • 1
  • 6
  • 18

2 Answers2

10

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)
kkiz
  • 31
  • 4
jpp
  • 159,742
  • 34
  • 281
  • 339
5

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)
sophros
  • 14,672
  • 11
  • 46
  • 75