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


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

Updated on: 19-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements