Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 506
James Avatar asked Dec 04 '18 11:12

James


1 Answers

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)
like image 116
jpp Avatar answered Sep 23 '22 19:09

jpp