Ricochet_Bunny
Ricochet_Bunny

Reputation: 547

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

Upvotes: 9

Views: 39602

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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

Upvotes: 29

Lu.nemec
Lu.nemec

Reputation: 512

there is built in function cmp, which you can use for the comparison

I needed to check if all items in list are identical, so I did this:

def compare(x, y):
    if x == y:
        return x
    return False

reduce(compare, my_list)

When you run this with say [1,1,1,1,1,1], it prints 1, when one of numbers doesn't match, it returns False .. simple

Upvotes: 0

Somesh
Somesh

Reputation: 1295

you can also use inbuilt reduce function

e.g. :

l = [1,2,3,4,5,6,7]

def my_function(a,b):
    # your comparison between a and b
    # return or print values or what ever you want to do based on the comparison


reduce(my_function, l)

reduce will automatically take care of i and i + 1.

Hope it helps. :)

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318508

The quick-and-ugly solution would be this (don't use it!):

for i, item in enumerate(lst):
    # here you can use lst[i + 1] as long as i + 1 < len(lst)

However, do not implement list sorting by yourself! Use .sort() to sort in-place or sorted() if you want to create a new list instead. There is a really good guide on how to sort things on the python website.

If that's not your intention.. instead of the loop I posted above there's also a much nicer way to iterate over chunks from a list in another SO question:

import itertools
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

You use to like this:

for x, y in grouper(2, lst):
    # do whatever. in case of an odd element count y is None in the last iteration

Upvotes: 4

Related Questions