Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two adjacent items in the same list - Python

I am searching for a way to compare two adjacent items in a list, eg. comparing which has a higher value, and then I will sort them accordingly. It is a list the user will be inputting, so it is not a case of just if l[1] > l[2], as I will not know the length of the list, so I will need a general statement for use in a for loop.

I had the idea of having something akin to for i in l: if x > i[index of x + 1] but do not know how to find the index of the variable. Any help appreciated, Thank you

EDIT: I am aware of the built in sort function, but just wanted to practice coding and algorithm-writing by creating my own :)

like image 841
Ricochet_Bunny Avatar asked Dec 23 '12 16:12

Ricochet_Bunny


1 Answers

You can use zip():

In [23]: lis = [1,7,8,4,5,3]

In [24]: for x, y in zip(lis, lis[1:]):
   ....:     print x, y           # prints the adjacent elements
             # do something here
   ....:     
1 7
7 8
8 4
4 5
5 3
like image 59
Ashwini Chaudhary Avatar answered Sep 22 '22 14:09

Ashwini Chaudhary