0

I was trying to find the second largest number in a list and thought of converting list into set, and to convert it back to list to eliminate the repeated values. Unfortunately, the negative value took the last index of the set (where I expected the greatest value to occupy the last index in the set). List contains both negative and positive values. When it was converted to set, the negative value took the last index.

n = 5
arr = [57, 57, 57, -57, 57]

res = list(set(arr))
print(res[-2])

I expected this to be my output:

-57

but the one I got was:

57

How do I find the second largest number in a list?

Vlad
  • 8,225
  • 5
  • 33
  • 45
Abilash S
  • 3
  • 3

2 Answers2

0

Sets have arbitrary ordering. You can't rely on any particular ordering (it's simply not part of the language spec, so it can change from release to release, or even run to run in theory, and in practice for strings).

Either sort the list, or use heapq.nlargest to find the second largest number. In either case, set is only useful for deduplication, you'll need to convert back to list to get useful ordering.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Here

arr = [57, 57, 57, -57, 57]

# If you want to avoid duplicates:
second_largest  = sorted(list(set(arr)))[-2]


# If you dont care about duplicates:
second_largest = sorted(arr)[-2]
balderman
  • 22,927
  • 7
  • 34
  • 52