pythonlistfor-looptry-exceptindex-error

Are there any priority "or" in python?


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


Solution

  • 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])