0

I am trying to figure out a way to find whether all the integers in my list are increasing sequentially. If any numbers are non-sequential I want to get the index.

mylist = [1,2,3,2]

So, is 2 more than 1 (yes), is 3 more than 2 (yes), is 2 more than 3(no, get index).

I can compare an unsorted list against a sorted list to work out if it is sequential, but I also want to establish the index. Is there a way to do this?

Thanks Toby

1
  • 1
    Is [1,2,4] also considered valid sequence in your example? Commented Nov 26, 2014 at 14:56

3 Answers 3

1

I guess you are looking for something like this:

>>> mylist = [1,2,3,2,3,5,6,3,7,8,6]
>>> [i+1 for i in range(len(mylist)-1) if mylist[i]>mylist[i+1]]
[3, 7, 10]
Sign up to request clarification or add additional context in comments.

Comments

1

This should do the trick:

def nonincr_index(l):
    if not l:
        return 0
    prev=l[0]
    for n,i in enumerate(l):
        if i<prev:
            return n
        prev=i
    return len(l)

>>> nonincr_index([1,2,3,2])
3

It returns the index of the non increasing item.

Comments

1

You can use enumerate to do this for you:

In [1]: mylist = [1,2,3,2]

In [2]: for idx, element in enumerate(mylist):
   ...:     if idx+1 != element:
   ...:         print element, idx
   ...:         
2 3

In case your sequence can start from any number,

In [1]: mylist = [2,3,4,2,7]

In [2]: for idx, element in enumerate(mylist):
   ....:    if idx + mylist[0] != element:
   ....:           print element, idx
   ....:         
2 3
7 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.