Question 10 List Practice

Screen Link:
https://app.dataquest.io/m/1018/lists/10/finding-the-first-occurrence

My Code:

def find_first(some_list, element):
    if element in some_list:
        return some_list.index(element)
    else: 
        return -1
    

What the suggested answer is:

def find_first(some_list, element):
    try:
        return some_list.index(element)
    except:
        return -1

I am not sure if my code is correct or not in this case, The Interface actually approves my code, but I just want to know why the answer is using ( try…except..) instead of using (if…else…)

1 Like

Hi @jinyushan1990, the 2 codes largely do the same thing. try and except are used to handle errors (or exception) in codes. In the case of your code, when the find_first() function is called, the code in try: block, i.e., return some_list.index(element) will be executed. Assuming there is no element in some_list, an error occurs and when this happens, the code in the except: block, i.e., return -1, will be executed.

So essentially, the try block lets you test a block of code for errors and the except block lets you handle the error. In this case, I guess you see how the codes are similar.

You may read more about try and except here.

2 Likes

It make a lot of sense. Thanks for explaining this! :raised_hands:

Glad you find my response helpful!