if lst[3] == 'test':
pass # Do something
else:
pass # Do something
Sometimes the above code gives index error when the list doesn't have sufficient items.
In order to handle index error I do:
try:
if lst[3] == 'test':
pass # Do something
else:
pass # Do something
except IndexError:
pass # Handle the exception
Is there any other better way to handle this - for example by checking the length, but without code duplication of the else block? Example of duplicate code in the else block:
if len(lst) > 3:
if lst[3] == 'test':
pass # Do something
else:
pass # Do something
else:
pass # Do the same thing as in the previous else