I had this question come up in a job interview, and I was wondering if there were different ways to solve this. Preferably using Python 3.
Given a list of [20,40,20,60,80] find the second highest number.
The idea is to remove the duplicates. In one solution I've iterated over the list, and added any unique values to a list of uniques. Another way I did it was to convert the list to a set and back to a list, and then grab the second number.
So here's the question. Is there a better way to do this using Python 3?
Here's my code for solving in two different ways.
def second_item_method_1():
my_list = [20,40,20,60,80]
my_set = set(my_list)
my_list = list(my_set)
my_list.sort()
print(my_list[1])
def second_item_method_2():
my_list = [20,40,20,60,80]
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
print(my_list[1])
second_item_method_1()
second_item_method_2()
Any other possible solutions?