Python IndexError: tuple index out of range Solution

Posted in /  

Python IndexError: tuple index out of range Solution
vinaykhatri

Vinay Khatri
Last updated on November 8, 2024

    Similar to Python lists , Python tuples also support indexing to access its individual elements. Although indexing provided an efficient way to access tuple elements, if we try to access a tuple element that does not exist, we get the IndexError: tuple index out of range Error.

    In this Python guide, we will walk through this Python error and discuss how to solve it. To get a better idea about this error, we will also demonstrate this error using a tuple. Let's get started with the Error statement.

    Python Error: IndexError: tuple index out of range

    The Error Statement IndexError: tuple index out of range is divided into two parts Exception Type and Error Message .

    1. Exception Type ( IndexError ): IndexError generally occurs in Python when we try to access an element with an invalid index number.
    2. Error Message( tuple index out of range ): This error message is telling us that we are trying to access a Python tuple element with an invalid index number. The index out of the range means we are trying to pass an index number that is out of the tuple index range.

    Error Reason

    A tuple stores its elements in sequential order and uses indexing. The indexing range of the tuple starts from 0 up to n-1, where n is the total number of elements present in the tuple.

    For instance, if a tuple has 4 elements, then the range of that tuple will start from 0 and goes upto 3. This means we can only access tuple elements using index values 0, 1, 2, and 3. But if we try to access a tuple element that does not exist using index 4 and above, then we will receive the tuple index out of range error .

    Example

    # tuple with 4 elements
    my_tup = ('a', 'b', 'c', 'd')
    
    # access tuple index 4 element (error)
    print(my_tup[4])

    Output

    Traceback (most recent call last):
    File "main.py", line 5, in <module>
    print(my_tup[4])
    IndexError: tuple index out of range

    Common Error Scenario

    The tuple index out of range is a common error, and many new Python learners commit this error when they put the wrong logic while handling the tuples.

    Let's say we have a tuple with 6 elements in it. We need to access the 3 last elements of the tuple and their index value along with them. For this, we will use a for loop along with the range statement.

    # tuple with 6 elements
    letters = ('a', 'b', 'c', 'd', 'e', 'f')
    
    for i in range(3, 7):
        print(f"{i}---> {letters[i]}")

    Output

    3---> d
    4---> e
    5---> f
    Traceback (most recent call last):
    File "main.py", line 5, in <module>
    print(f"{i}---> {letters[i]}")
    IndexError: tuple index out of range

    Break the code

    In the output, we are getting the last 3 elements of our tuple letters .But we are also getting the tuple index out of range error. This is because the range(3,7) statement is creating an iterable object from a range 3 to 6 , and the range of tuple letters support only 0 to 5 . So when the i value becomes 6, and it tries to access the letters[6] value, Python throws the "tuple index out of range" error because there is no letters[6] element in the tuple.

    Solution

    To solve the above problem, we need to make sure that the range value only goes from 3 to 5 so we can get the last 3 elements and their index values. For that, we need to put the starting range parameter to 3 and the ending parameter to 6. So the range starts from 3 and ends at 5.

    # tuple with 6 elements
    letters = ('a', 'b', 'c', 'd', 'e', 'f')
    
    for i in range(3, 6):
        print(f"{i}---> {letters[i]}")

    Output

    3---> d
    4---> e
    5---> f

    Final Thoughts!

    The tuple index out of range is a Python IndexError. It raises when we try to access a tuple element that does not exist, using an out-of-range index value. While accessing tuple elements, we can only access those elements whose index value ranges from 0 to n-1, where n is the total number of elements present in the tuple.

    You will only encounter this error in Python when you miscalculate the tuple index range while accessing the tuple element.

    If you are encountering this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.

    People are also reading:

    Leave a Comment on this Post

    0 Comments