0

Is there any "priority or" function in python? For instance if i am out of range

vec = [1, 2, 3, 4, 5]
new_vec = []

for index, number in enumerate(vec):
    try:
    new_value += vec[index + 1] + vec[index + 2] or if i am out of range do += vec[index +1] and if i am still out of range pass
except IndexError:
    pass 

The problem with my "pass" is that it will either do vec[index + 1] + vec[index + 2] or pass however I want to do vec[index + 1] if vec[index + 1] + vec[index + 2] not possible and if vec[index + 1] is not possible I want to pass. For instance the 4 in vec has the situation vec[index + 1] but for the 5 we would pass

ZedORYasuo
  • 183
  • 7
  • Does this answer your question? [Example use of "continue" statement in Python?](https://stackoverflow.com/questions/8420705/example-use-of-continue-statement-in-python) – David Parks Nov 30 '22 at 21:48
  • Side note: Those values are lists, not vectors. Calling them `vec` and `new_vec` is misleading. – ChrisGPT was on strike Nov 30 '22 at 21:48
  • 1
    Nope. You're best checking your index bounds `index + 2 < len(vec)`, or using a try-except as you are now. Side-note: dictionaries do have a `.get()` method like that. – Noah May Nov 30 '22 at 21:56
  • Actually, you can do `sum(vec[index + 1: index + 3], start=default_sum)` since you can slice a list out of range with no errors. – Noah May Nov 30 '22 at 21:58
  • Not sure about the second solution, however the first you said with index + 2 < len(vec) worked – ZedORYasuo Nov 30 '22 at 22:03
  • Would you please explain the second solution in more details or show an example? @NoahMay – ZedORYasuo Nov 30 '22 at 22:03

1 Answers1

1

You can use sum() and regular list slicing. Unlike regular indexing which raises an error when out of range, slicing continues to work.

five = [0, 1, 2, 3, 4]

print(five[4]) # 4
print(five[5]) # Error
print(five[2:4]) # [2, 3]
print(five[2:1000]) # [2, 3, 4]; no error
print(five[1000:1001]) # []; still no error

For your usecase, you can do:

new_value += sum(vec[index + 1: index + 3])
Noah May
  • 1,049
  • 8
  • 18
  • Do you know if the same technique would work for the three previous values also? I did: new_value += sum(vec[index - 3 :index + 1]), but if one index did only have 1 index before (instead of 3) it did not sum that up just passed – ZedORYasuo Dec 01 '22 at 09:41