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 :)
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
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