Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

REPOST, PLEASE HELP: Please help me define the following function in Python: Con

ID: 3938058 • Letter: R

Question

REPOST, PLEASE HELP:

Please help me define the following function in Python:

Consider a list of values, xs. Find and return the value at location index.
If index is invalid for xs, return response instead. Remember that .get()
for dictionaries works gracefully for non-existing keys. Here we are
implementing a get() function for list type.

Parameters:
- xs :: list of values of any length.
- index :: an integer, specifying which value in the list to return.
- response :: a python value, to be returned when index is invalid for the list. Defaults to None.
- Return value: a value from xs at index or the pre-set response.

- Suggestion: use try-except blocks in your solution.

Examples:
- get(['a','b','c'],0) --> 'a'
- get(['a','b','c'],3) --> None
- get(['a','b','c'],4,"oops") --> 'oops'

def get(xs, index, response=None):

Explanation / Answer

Please find the required program along with its output. Please see the comments against each line to understand the step.

def get(xs, index, response=None):
  
   if(index >= len(xs)):   #if the index is more than or equal to length+1 (+1 because it starts from 0), then return response
       return response
   else:   #else iterate over all elements in the list and return the element at position index
       i = 0;
       for x in xs:
           if(i==index):
               return x
           i = i+1
          
          
print (get(['a','b','c'],0) )   #tests
print (get(['a','b','c'],3))
print (get(['a','b','c'],4,"oops"))
      

-------------------------------------------------------

OUTPUT: