Search code examples
pythontry-exceptindex-error

How to catch specific index error in Python and attach new value for this?


I want to return None only if i catch Index out of range for the value in issue

 def extract_values(values):
     try:
         first = values[0]
         second = values[1]
         last = values[3]
     except IndexError:
        first = "None"
         last = "None"
        second = "None"
     return first,second,last
 # test
 list_values = ["a","b","c"]    
 print(extract_values(list_values))


actual result with this code :
('None', 'None', 'None') 
missed result  :
('a', 'b', 'None')

Solution

  • There must be a more elegant answer to that but you can do :

    def extract_values(values):
        try:
            first = values[0]
        except IndexError:
            first = None
        try:
            second = values[1]
        except IndexError:
            second = None
        try:
            third = values[3]
        except IndexError:
            third = None
        return first, second, third