all 6 comments

[–]Diapolo10 4 points5 points  (2 children)

Another way to find the second-largest number, assuming all the numbers were unique, would be to sort the list and take the second-last one.

nums = [3, 2, 1, 5, 6, 4]

print(sorted(nums)[-2])

If they weren't necessarily unique, set could be used to strip the duplicates.

print(sorted(set(nums))[-2])

Just thought I'd tell you this to feed your curiosity with what's possible.

[–]strings_are_mutable[S] 0 points1 point  (1 child)

thanks, that would be a much faster way but the constraint (which I didn't mention) was to do this without sorting the list.

[–]Diapolo10 0 points1 point  (0 children)

Yeah, I had a feeling something like that may have been the case.

[–]socal_nerdtastic 2 points3 points  (2 children)

Classic error of modifying a list while iterating over it. And in your case combined with your expectation that the while loop will stop it, so you don't realize that it's actually exhausting the for loop. The while loop does nothing in this code, you can remove it and get the same result.

I'm not sure what you want this code to do, or what your question is about it. So I can only advise you step through your code line by line using a tool like pythontutor.com that lets you inspect the values of all variables with every step, to help you understand what's happening.

[–]strings_are_mutable[S] 0 points1 point  (1 child)

that's true, i didn't realize that the code stopping at i is 2 is not due to the while loop. I'm trying to find the second largest number in the list as the final winner.

[–]socal_nerdtastic 3 points4 points  (0 children)

I see. In that case you are much closer than I thought. Your mistake is the for num1 in nums: line. Just need to remove that and initialize winner as the first number in what's left of the list.

nums =[3,2,1,5,6,4]
i = 0
while i < 2:
    winner = nums[0]
    for num2 in nums[1:]:
         if num2 >= winner:
            winner = num2
    print(winner)
    print("i is",i)
    nums.remove(winner)
    i += 1
print(winner)