-5

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')
Dhayf OTHMEN
  • 71
  • 1
  • 8
  • 3
    And what problem you you have? Please take some time to refresh [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Aug 12 '19 at 08:10
  • 1
    just use an if else statement to check – Mox Aug 12 '19 at 08:12
  • 2
    Whole function body: `return [values[i] if i < len(values) else None for i in (0, 1, 3)]` – Matthias Aug 12 '19 at 08:36

1 Answers1

0

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
Pouple
  • 86
  • 6
  • thank you , i was found another solution that looks like your code (the same instruction just i added some block to catch another exception related to the length of my data. – Dhayf OTHMEN Aug 12 '19 at 10:01
  • 1
    I still think the solution I presented in the comments is better. – Matthias Aug 12 '19 at 13:05