r/PythonLearning • u/RegularBother614 • 9d ago
What do you guys think?
I made a program that finds the second largest digit in a list.
Using the list method "remove()" and "max" function. Python is COOL!
88
Upvotes
View all comments
1
u/AdDiligent1688 9d ago edited 9d ago
This won’t work if there are duplicates of the max such as [3,2,3,1]. the second largest in this case is 2. .remove only removes the first occurrence of a number, so your program will still output 3; sorted or .sort also won’t work here either, unless you convert it to set first then sort it, but as other pointed out with sorting this is O(n log n) worst case. There is a O(n) worst case solution to this using a single pass in a loop as well to get second largest. Look at the third solution here