If list exists Python

  1. HowTo
  2. Python How-To's
  3. Check if Index Exists in Python List

Check if Index Exists in Python List

Python Python List

Created: October-19, 2021 | Updated: December-25, 2021

We will introduce two methods to check if a list index exists using the list range and the IndexError exception.

Check if Index Exists in Python List Using the List Range

We will have to check if the index exists in the range of 0 and the length of the list.

fruit_list = ['Apple','Banana','Pineapple'] for index in range(0,5): if 0 <= index < len(fruit_list): print("Index ",index ," in range") else: print("Index ",index," not in range")

Output:

Index 0 in range Index 1 in range Index 2 in range Index 3 not in range Index 4 not in range

Check if Index Exists in Python List Using The IndexError

When we try to access an index that does not exist in a list, it will raise an IndexError exception.

fruit_list = ['Apple','Banana','Pineapple'] for index in range(0,5): try: fruit_list[index] print("Index ",index," in range") except IndexError: print("Index ",index," does not exist") Index 0 in range Index 1 in range Index 2 in range Index 3 does not exist Index 4 does not exist
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Multiply Two Lists in Python
  • Sort a List of Lists in Python
    • Make a Pascal's Triangle in Python
    • Exit Program With the if Condition in Python
    If list exists Python
    report this ad