Python Forum

Full Version: How to terminate a list of inputs with a set value? SOS
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am attempting to make a program in Python 3.7 where you would input integers one after another until you terminate it by entering the value -3. Once you input -3, the program would print the second highest number you've listed.

My current code is:
a=[]
n=int(input("Enter number:"))
  for i in range(1,n+1):
  n=int(input("Enter number:"))
  a.append(n)
    if n == -3:
      break
a.sort()
print("Second largest number is:",a[n-2])
I keep getting the error:
Error:
Traceback (most recent call last): File "main.py", line 9, in <module> print("Second largest number is:",a[n-2]) IndexError: list index out of range
If anyone could help me out it would be greatly appreciated as I am still a beginner with this language.
Please read https://python-forum.io/misc.php?action=help&hid=25 how to use code tags to format your question.
The error is because the first time your list a[] will have 1 item. So a[n-2] will yield a negative index. This is the error you get.
I don't see a "while" loop in your code. At least, you need to put "while True:" somewhere. You can use negative indexing to get the second element from the tail of a list. Finally, your solution is of O(n) space complexity (n the number of entered numbers); It would be useful if you try to find O(1) solution as well (i.e. without storing all entered numbers to a list).