Python Lists: How to Find Element Position with .index()

When working with Python lists, you often need to know “where (at which index) a specific element is located.” For example, checking “what number in the list corresponds to the ‘admin’ permission.” For such searches, use the list’s .index() method.

This article explains the basic usage of the .index() method and important points to note regarding duplicate or missing values.


目次

Basic Usage of .index()

The .index() method returns the index (number starting from 0) of the first occurrence of the specified value in the list.

Syntax:

list_variable.index(value_to_find)

Example:

# List of server roles
server_roles = ["auth-server", "db-server", "app-server", "log-server"]
# Index:             0              1             2              3

# Find the position of "app-server"
try:
    position = server_roles.index("app-server")
    print(f"'app-server' found at index {position}.")

except ValueError:
    print("'app-server' does not exist in the list.")

Output:

'app-server' found at index 2.

Note 1: Handling Duplicate Elements

If the value you are looking for exists multiple times in the list, .index() returns only the position of the first found element (the one with the lowest index). It does not return the second or subsequent indices.

# System log status list
log_statuses = ["OK", "OK", "ERROR", "OK", "TIMEOUT"]

# Search for "OK"
first_ok_index = log_statuses.index("OK")

print(f"Position of the first 'OK': {first_ok_index}")

Output:

Position of the first 'OK': 0

Although “OK” also exists at indices 1 and 3, only index 0 is returned.


Note 2: When the Element Does Not Exist (ValueError)

The most important thing to remember about .index() is that if the specified value does not exist in the list at all, it raises a ValueError, and the program stops.

# List of server roles
server_roles = ["auth-server", "db-server", "app-server"]

# Try to find "cache-server" which is not in the list
try:
    pos = server_roles.index("cache-server")
    print(f"Position: {pos}")
except ValueError as e:
    print(f"An error occurred: {e}")

Output:

An error occurred: 'cache-server' is not in list

Safe Search Method (Using with in operator)

To search for a position safely without triggering a ValueError, it is common to first check if the element exists using the in operator.

target_role = "db-server"
target_role_unknown = "cache-server"

def find_index_safely(roles, target):
    """
    Check existence with 'in' operator before calling .index()
    """
    if target in roles:
        position = roles.index(target)
        print(f"'{target}' exists at index {position}.")
    else:
        print(f"'{target}' was not found in the list.")

# Execution
find_index_safely(server_roles, target_role)
find_index_safely(server_roles, target_role_unknown)

Output:

'db-server' exists at index 1.
'cache-server' was not found in the list.

By performing a pre-check with the in operator, you can avoid ValueError and run the program safely.


Summary

  • Use the .index(value) method to find the position (index) of an element in a list.
  • If there are duplicates, it returns only the first index found.
  • If the value does not exist, it raises a ValueError.
  • To avoid errors, use the in operator (e.g., if value in my_list:) to confirm existence before calling .index().
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次