• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / IndexError in Python

IndexError in Python

Author: Aditya Raj
Last Updated: December 28, 2022

Lists are one of the most used data structures in Python. You might have gotten the message “IndexError: list index out of range” when your program ran into an error while using lists. In this article, we will discuss how to avoid this error by studying the IndexError in Python.

Table of Contents
  1. What is an IndexError in Python?
  2. How to Avoid IndexError in Python?
    1. Preempt IndexError Using If-Else Blocks
    2. Handle IndexError Using Try-Except Blocks
  3. Conclusion

What is an IndexError in Python?

IndexError is an exception in python that occurs when we try to access an element from a list or tuple from an index that is not present in the list. For example, we have a list of 10 elements, the index is from 0 to 9. If we try to access an element at index 10 or 11 or more, it will cause the program to raise IndexError with the message “IndexError: list index out of range”  as follows.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The list is:", myList)
index = 10
element = myList[index]
print("Element at index {} is {}".format(index,element))

Output:

The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
    element = myList[index]
IndexError: list index out of range

Similarly, if we have a tuple consisting of 10 elements, the index of the elements is in the range 0 to 9. If we try to access an element at index 10 or more, the program will cause IndexError as follows.

myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
element = myTuple[index]
print("Element at index {} is {}".format(index,element))

Output:

The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
    element = myTuple[index]
IndexError: tuple index out of range

Here, we have tried to access an element at index 10 from a tuple having only 10 elements. Hence, the program runs into an IndexError exception.

How to Avoid IndexError in Python?

We can either handle the index error exception or preempt it. To preempt, we can use if-else blocks. To handle the exception once it has occurred, we can use exception handling in Python.

Preempt IndexError Using If-Else Blocks

The only way to avoid an IndexError in python is to ensure that we do not access an element from an index that is out of range. For example, if a list or a tuple has 10 elements, the elements will only be present at indices 0 to 9. So, we should never access the element at index 10 or more. To do this, we can use if-else statements to check if the index is in the correct range or not as follows.

myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
if index <= 9:
    element = myTuple[index]
    print("Element at index {} is {}".format(index, element))
else:
    print("Index should be smaller.")

Output:

The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.

Handle IndexError Using Try-Except Blocks

Alternatively, we can use python try except blocks to handle the IndexError exception after the program raises it. Using this way, we cannot avoid the IndexError exception but we can make sure that the program doesn’t terminate prematurely after IndexError is raised. 

myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
try:
    element = myTuple[index]
    print("Element at index {} is {}".format(index, element))
except IndexError:
    print("Index should be smaller.")

Output:

The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.

Conclusion

In this article, we have discussed IndexError in python. We have also discussed ways to above this exception. You can read more about python lists in this article on list comprehension.  

To learn more about python programming, you can read this article on string manipulation. You might also like this article on python simplehttpserver.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us