user2942337
user2942337

Reputation: 39

Using Lists in Python

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

Upvotes: 0

Views: 104

Answers (2)

mamalos
mamalos

Reputation: 97

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]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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

Upvotes: 9

Related Questions