Motivation

From a HackerRank challenge.

Example problem

  • Say you have the list [1,3,4,5,5,6,6,6]. The expected output should be 5.

The solution

  • Use set to filter out any duplicate numbers.
  • Use sorted to sort the numbers in ascending order. Can specify reverse = True if descending order is desired.
  • Then access the second last number in the list by indexing.
1
2
3
4
5
6
7
alist = [1,3,4,5,5,6,6,6]

# first remove duplicates
no_duplicates = set(alist)

# then sort the list and access second last item
print(sorted(no_duplicates)[-2])

And you will get 5!

References

  • More on slicing/indexing here.