Reputation: 21
In Python when I define a range for a variable, for example
for i in range(0,9):
but here I want to prevent i
from taking a value of 7
. How can I do this?
Upvotes: 0
Views: 4844
Reputation: 25997
Depends on what exactly you want to do. If you just want to create a list you can simply do:
ignore=[2,7] #list of indices to be ignored
l = [ind for ind in xrange(9) if ind not in ignore]
which yields
[0, 1, 3, 4, 5, 6, 8]
You can also directly use these created indices in a for loop e.g. like this:
[ind**2 for ind in xrange(9) if ind not in ignore]
which gives you
[0, 1, 9, 16, 25, 36, 64]
or you apply a function
def someFunc(value):
return value**3
[someFunc(ind) for ind in xrange(9) if ind not in ignore]
which yields
[0, 1, 27, 64, 125, 216, 512]
Upvotes: 2