0
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
Adirio
  • 5,040
  • 1
  • 14
  • 26
variable
  • 8,262
  • 9
  • 95
  • 215
  • IMHO, Exceptions are best way. Exceptions were designed to do this. It avoids boiler plate if-else and provides way to write clean code. If there are different kinds of exceptions, catch those specifically handle them. – drd Sep 08 '20 at 06:47
  • 1
    @drd if exceptions were designed to do this is a fight that will never have a clear winner. There will always be people telling you that common things to happen in code should never be exceptions, as exceptions by name are that, exceptions to the normal way of working. There will also always be people that tell you better to ask for forgiveneess that for permission. Both patterns have followers and detractors. – Adirio Sep 08 '20 at 06:50

5 Answers5

4

The trivial way would be to join both conditions using logical and:

if len(lst) > 3 and lst[3] == 'test':

As @YannickFunk mentioned in their answer, Python will short circuit the and operator and will immediately evaluate to False if len(lst) <= 3.

That being said, your question is slightly unclear. You ignore (pass) the exception in your first example but you "do something else" in the second.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

You can shorten it to

 if len(lst) > 3 and lst[3] == 'test':
     pass  # Do something
 else:
     pass  # Do something

Python short circuits the and operator and jumps into the else block if the len(lst) > 3 condition is not fulfilled.

Adirio
  • 5,040
  • 1
  • 14
  • 26
Yannick Funk
  • 1,319
  • 10
  • 23
0

Try this:

if len(lst) >= 3 and lst[3] == 'test':
    pass  # Do something
else:
    pass  # Do something
Adirio
  • 5,040
  • 1
  • 14
  • 26
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You could slice:

if 'test' in lst[3:4]:
superb rain
  • 5,300
  • 2
  • 11
  • 25
-1

As others altrady said, you could use a logical and

if len(lst) > 3 and lst[3] == 'test':

But I still would prefer to use the try/except block.

Which is the best choice may depend on what your code is supposed to do
Take a look at this question to learn more about what you should use

Adirio
  • 5,040
  • 1
  • 14
  • 26
Nicholas Obert
  • 1,235
  • 1
  • 13
  • 29