0

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?

Cleb
  • 25,102
  • 20
  • 116
  • 151
  • possible duplicate of [How to conditionally skip number of iteration steps in a for loop in python?](http://stackoverflow.com/questions/21169354/how-to-conditionally-skip-number-of-iteration-steps-in-a-for-loop-in-python) – BSMP May 30 '15 at 03:01

1 Answers1

2

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]
Cleb
  • 25,102
  • 20
  • 116
  • 151