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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With