Search code examples
pythonpython-2.7listbuilt-in

How to iterate over a list in python and get a booleans list of the compared values between each two close items?


I have a list full of objects and they contain an int for their age and I want to get another list that contains booleans only.

Each boolean states, if the object[i - 1] is either older for True or younger for False than object[i], or in other words, is the age to the item on my left is bigger or not than mine.

For example:

ls = [obj1(age = 5), obj2(age = 16), obj3(age = 4)]
result = [False, True]

I'm looking for a builtin function or a lean way to do so the shorter the better, preferably oneliner.


Solution

  • The simplest way is usually using zip

    [a.age > b.age for a, b in zip(ls, ls[1:])]
    

    It would be nice if there were a helper function pairs = lambda x: zip(x, x[1:]), but you can always define it yourself!