Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list is ascending by 1 in python

Tags:

python

I want to check if my given list is ascending by 1 or not

so:

[1,2,3,4] = True [1,3,4,5] = False

and if possible I want to do it with some python specific functions - so not looping it with a for if combination but something like all(... for values in list)

I hope this is clear

like image 399
Dominik Lemberger Avatar asked Jan 31 '26 03:01

Dominik Lemberger


1 Answers

How about this?

def has_stepsize_one(it):
    return all(x2 - x1 == 1 for x1, x2 in zip(it[:-1], it[1:]))
>>> has_stepsize_one([1,2,3,4])
True

>>> has_stepsize_one([1,3,4,5])
False

This should work with any collection, not just lists.

Keep in mind that this returns True for collections with less than two elements:

>>> has_stepsize_one([1])
True

>>> has_stepsize_one([])
True

If you don't want that, you'll have to check the length of the iterator.

For generic iterators that don't support getitem, comparing to itertools.count is probably the best way to do it (similar to kaya3's answer):

import itertools

def has_stepsize_one(it):
    it = iter(it)
    try:
        first = next(it)
    except StopIteration:
        return True

    return all(x == y for x, y in zip(it, itertools.count(first + 1)))
>>> has_stepsize_one((i for i in range(10)))
True
like image 191
Dion Avatar answered Feb 01 '26 16:02

Dion