Hi All,

Beginner programmer here with an easy question I hope. I want to be able to compare the value of the first item in a list to the second item in the list to see if they are sequential.
so in this list: numblist = [1 , 2 , 3, 5, 6, 7, 8, 9, 11]
i want to be able to report on the gaps between 3-5 and 9-11 in the most efficient way.

My first try was to take the list and run the following for loop:

for i in numblist:
    if numblist[i] == numblist[i + 1] - 1:
        print 'yay'
    else:
        print 'gap'

But this creates an error when it gets to the last item in the list: IndexError: list index out of range. So what methods are available for referencing the next, previous and last items in sequential data?

You have simple use the try/except error routine:

numblist = [1 , 2 , 3, 5, 6, 7, 8, 9, 11]

for i in numblist:
    try:
        if numblist[i] == numblist[i + 1] - 1:
            print 'yay'
        else:
            print 'gap'
    except:
        pass

Iterate on all the list elements except the last one:

numblist = [1, 2, 3, 5, 6, 7, 8, 9, 11]

for i in range(len(numblist)-1):
    if numblist[i] == numblist[i + 1] - 1:
        print 'NO GAP between indexes %d and %d' % (i, i+1)
    else:
        print 'GAP between indexes %d and %d' % (i, i+1)

Output:

NO GAP between indexes 0 and 1
NO GAP between indexes 1 and 2
GAP between indexes 2 and 3
NO GAP between indexes 3 and 4
NO GAP between indexes 4 and 5
NO GAP between indexes 5 and 6
NO GAP between indexes 6 and 7
GAP between indexes 7 and 8

Both of those solutions worked well. Thanks so much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.