a quickie: range - x

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Nov 29 23:17:10 EST 2006


On Wed, 29 Nov 2006 19:42:16 -0800, rjtucke wrote:

> I want an iterable from 0 to N except for element m (<=M).
> I could write
> x = range(N)
> x.remove(m)
> but I want it in one expression.

Because the world will end if you can't?

What's wrong with the solution you already have? If you need to use it
many times, make it a function. Calling the function is always a one-liner.

Here's another solution:

x = [i for i in range(N) if i != m]

Here's another:

x = range(m-1) + range(m+1, N)

Here's a generator to do it:

def range_except(N, m):
    """Iterator that returns ints from 0 through N-1 except for m."""
    for i in xrange(N):
        if i != m:
            yield i




-- 
Steven.




More information about the Python-list mailing list