Python Forum
How to terminate a list of inputs with a set value? SOS - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to terminate a list of inputs with a set value? SOS (/thread-21198.html)



How to terminate a list of inputs with a set value? SOS - Manning - Sep-18-2019

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.


RE: How to terminate a list of inputs with a set value? SOS - ibreeden - Sep-18-2019

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.


RE: How to terminate a list of inputs with a set value? SOS - scidam - Sep-19-2019

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).