Search code examples
pythonlist-comprehension

How to go through a python list one by one?


I am trying to make an algorithm that finds which number is out of order in a group of numbers.

Is there a way to go through the list and see if adding 1 to each item on the list makes the value of the next item on the list. Example ( 0 + 1 == 1) and ( 1 + 1 = 2) but when you get to (2 + 1 != 4) how would I make it display a 3.

number = [0,1,2,4,5]

if number[0] + 1 != number[1]:

Solution

  • You can compare each number with its relative position (starting at the first value):

    if any(i!=n for i,n in enumerate(a,a[0])):
       print("out of order")
    else:
       print("proper sequence")
    

    You could also use zip to compare each item with its successor:

    if any(m-n != 1 for n,m in zip(a,a[1:])):
       print("out of order")
    else:
       print("proper sequence")