Let's consider this example - code that returns index of the first None
value in the list li
(if present) or the last element's index if None
is not present in li
.
I could possibly check for None being in list but using ifs isn't the preferred way - Dive Into Python encourages to use exceptions as they are said to be faster and make code cleaner (see this question). So I came with three approaches:
1.
try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1
print my_index
my_index
is declared inside try/except block. Less lines, no redundant declaration. Possible problem - different exception type will result in not creating my_index
and crashing the script on print
.
2.
my_index = None # or anything else
try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1
print my_index
my_index
is declared before try/except and has a value assigned regardless of what exception happens. Cons - more lines, looks redundant.
3. edit: Won't work - finally is executed regardless of try/except results
try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1
finally:
my_index = None # or anything else
print my_index
Pros - always works (or at least I think so). Cons - I have never ever seen anyone using finally
for my entire Python experience which must happen for a reason.
Which of these methods is considered the preferred and pythonic way? Maybe there is some better solution?