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?

1

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.