What is the best way to handle list empty exception in Python?

PythonServer Side ProgrammingProgramming

List is an ordered sequence of elements. Individual element in list is accessed using index starting with 0 and goes up to length-1. If index goes beyond this range, IndexError exception is encountered.

In following example, an infinite loop is used to pop one element at a time. As loop tries to go even after last element is popped, IndexError exception will be encountered. We trap it using try – except mechanism.

a=[1,2,3]
while True:
  try:
    b=a.pop()
    print (b)
  except (IndexError):
    break
raja
Published on 09-Jan-2018 09:13:54
Advertisements