Search code examples
listpython-3.xreturnlocation

Finding and returning the value at location index in a list


Could my current code work for this function? Here is the goal of what I am trying to do first and then my current attempt

Look at list of values, xs. Find and return the value at location index. When index is invalid for xs, return response instead.

Current code:

def get(xs, index, response=None):
    xs=[]
    i=0
    for i in xs:
        try:
            while i<len(xs):
                index=xs.index(xs,index)
                index = i
            return i 
        except:
            return response

Thanks any help is appreciated


Solution

  • You seem to be very confused about what you are trying to do...

    So if I understand correctly you want to return xs[index] if it exists otherwise response, a simple way to do that following the EAFP principle is:

    def get(xs, index, response=None):
        try:
            return xs[index]
        except IndexError:
            return response