0

I'm trying to rewrite this code using lists. Raise index crashes the program if I > 4. How can I make this code smaller using lists? Any help is appreciated.

if (I == 0):
  J = -12
elif (I == 1):
  J = 24
elif (I == 2):
  J = -6
elif (I == 3):
  J = 193
elif (I == 4):
  J = 87
else:
  raise IndexError

2 Answers 2

9

Just use a list with the possible values of J:

J_values = [-12, 24, -6, 193, 87]
J = J_values[I]

This raises an IndexError exception if I is out of bounds, so greater than 4:

>>> J_values = [-12, 24, -6, 193, 87]
>>> J_values[2]
-6
>>> J_values[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Negative indices would count from the end of the list; -1 being the last element:

>>> J_values[-1]
87
Sign up to request clarification or add additional context in comments.

Comments

0

Additionally to @Martijn Pieters' reply, if your values follow a specific pattern, you can use range() when creating your list:

>>> J_VALUES = range(15)
>>> J_VALUES
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
>>> J_VALUES = range(-5, 15, 2)
>>> J_VALUES
[-5, -3, -1, 1, 3, 5, 7, 9, 11, 13]

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.