Python Interview Questions — 1
Nov 4 · 2 min read
Question: Implement a function that finds the second largest element in a list?
Answer: Before you start with the implementation need to ask some clarifying questions to the interviewer in order to identify what are the assumptions. For instance what happens:
- if the list is empty since there is no element in the list should the function return “None”?
- if there is only one element in the list,
- if the list is for instance [3, 2, 2, 1], what the function should return in this case “None” or “2”
Ask these kinds of questions and let the interview decide what function should return in this kind of cases.
def return_2nd_largest_elem(my_List):
largest = None
second_largest = None
if len(my_List) < 2:
print(" The length of the list is less than 2")
return None
# drop string elements if any
for element in my_List:
if type(element) == str:
print(f"Removing the detected string element: {element}")
my_List.remove(element)
#avoid duplicated elements if any
pxcmy_List = set(my_List)
for elem in my_List:
print ("elem : ",elem)
if largest == None:
largest = elem
elif elem > largest:
second_largest = largest
largest = elem
elif second_largest == None:
second_largest = elem
elif elem > second_largest:
second_largest = elemreturn second_largestYou can test the function for the following list test cases:
- L = [1,2,3,10,11,12,4,6,5,9,8, “caner”], for this input list the function should return 11
- L_1 = [0,-1,-2,-3], for this input list the function should return -1
- L_2 = [4,3,3,3,2,2,1,0], for this input list the function should return 3
- since there is no second element in the list should the function return “None” ?

