pythonrangeidioms

Omit one value from a range


What's the most concise way in Python to write a range (generator or list) which omits one single value. So given integers nand k with 0k<n I want all the integers from 0 (inclusive) to n (exclusive) but without k.


Solution

  • Since your list runs from 0 to n, we know that for all values n in the list ns, ns.index(n) == n. (ns[0] == 0, ns[1] == 1, and so on.)

    With that in mind, you could slice your list in this way:

    ns = range(n)
    ms = ns[:k] + ns[k+1:]
    

    Arguably shorter, but also arguably less clear, so up to you!