What happens by [-2] in Array?

Viewed 22
n = int(input())
arr = list(set(map(int, input().split())))
arr.sort()
print(arr[-2])    

I was expecting to get the 2nd highest number from a list . But I can't understand how the -2 works

2 Answers

A negative index counts backwards from the end of the list.

You could use .sort(reverse=True) and than access the second highest number with num[2]. -1 is the far side (the end of the list), -2 is the second last.

Related