The index() method of bytearray class in Python

The index() method returns the position of a subsequence in a given bytearray. It differs from the find() method that when the subsequence is not found it raises a ValueError.

Bytearray Updated 17 Dec 2025 1 min read

Overview

  • The index() method of bytearray class in Python returns the position at which a subsequence is found in a bytearray.
  • The index() method and the find() method are similar, but the index() method raises a ValueError when the given subsequence is not found in the bytearray.

Example:

python
# Example Python program that gets the

            # index of a given subsequence from a Python

            # bytearray

            ba = b"Between the woods and frozen lake"

            pos = ba.index(b"woods")

            print("Subsequence found at position:")

            print(pos)

Output

Output
Subsequence found at position:

12

Example

python
# Example Python program that raises an

            # exception when a subsequence is not found

            # in a Python bytearray

fromAPoem = b"A poem lovely as a tree."

            pos = fromAPoem.index(b"Plant")

            print(pos)

Output

Output
Traceback (most recent call last):

  File "/Users/vinodh/PythonProgs/ba_index_raise.py", line 6, in <module>

    pos = fromAPoem.index(b"Plant")

          ^^^^^^^^^^^^^^^^^^^^^^^^^

ValueError: subsection not found