Parsing numeric ranges

Alain Ketterlin alain at
Fri Feb 25 10:44:13 CET 2011

Seldon <seldon at> writes:

> I have to convert integer ranges expressed in a popular "compact"
> notation (e.g. 2, 5-7, 20-22, 41) to a the actual set of numbers (i.e.
> 2,5,7,20,21,22,41).

What form does the input have? Are they strings, or some other

> Is there any library for doing such kind of things or I have to write
> it from scratch ?

What kind of result do you need? An explicit list? A generator?

Here is a naive solution where the input is a list of strings and the
result a generator:

def values(l):
    for item in l:
        bounds = item.split('-')
        if len(bounds) == 1:
            yield int(bounds[0])
        elif len(bounds) == 2:
            for v in range(int(bounds[0]),1+int(bounds[1])):
                yield v
            pass # ignore, or throw, or...

# Use as in:
for x in values(["1","2-3","4-10"]):
    print x

-- Alain.

More information about the Python-list mailing list