A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3schools.com/python/ref_exception_indexerror.asp below:

Website Navigation


Python IndexError Exception

Python IndexError Exception

❮ Python Exceptions

Example

A IndexError occurs if you try access a list item with an index that does not exist:

x = ["apple", "banana", "cherry"]
print(x[5])

Try it Yourself » Definition and Usage

The IndexError exception occurs when you use an index on a sequence, like a list or a tuple, and the index is out of range.

You can handle the IndexError in a try...except statement, see the example below.

Exception Handling Example

Handling the IndexError in a try...except statement:

x = ["apple", "banana", "cherry"]
try:
  print(x[5])
except IndexError:
  print("You are trying to access an item that does not exist!")
except:
  print("Something else went wrong")

Try it Yourself »

❮ Python Exceptions

Track your progress - it's free!


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4