Desura
Desura

Reputation: 175

range() with a 'forbidden' value?

Let's have an example. I have an ordinary function like this:

def function(x):
    for b in range(0, 5):
        print(b)

I want to have x as an exception in the range; this way, it would do something like this:

def function(x):
    for b in range(0, x):
        print(b)
    for b in range(x+1, 5):
        print(b)

But if what I want to do is longer than a simple print(), it will extend my function a lot. Is there any solution for doing that?

Upvotes: 0

Views: 199

Answers (2)

martineau
martineau

Reputation: 123491

The two sub-ranges could be "chained" together:

from itertools import chain

def function(x):
    for b in chain(range(0, x), range(x+1, 5)):
        print(b)

Or you could also use a generator expression:

def function(x):
    for b in (v for v in range(0, 5) if v != x):
        print(b)

The latter can easily be generalized to support the exclusion of multiple values:

def function(*x):
    for b in (v for v in range(0, 5) if v not in set(x)):
        print(b)

function(3)     # -> 0 1 2 4
function(1, 3)  # -> 0 2 4

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1123490

Skip x inside the loop:

for b in range(0, 5):
    if b == x:
        continue  # skip to next iteration
    print(b)

Upvotes: 3

Related Questions