Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. list.index() / list.count() / in Operator

list.index() / list.count() / in Operator

Methods and operators for searching elements in a list and checking whether a specific value is present.

Syntax

# Returns the index of the first element matching the value.
list.index(value, start=0, end=len(list))

# Returns the number of elements matching the value.
list.count(value)

# Checks whether the list contains the value (True / False).
value in list
value not in list

Method and Operator List

Method / OperatorDescription
list.index(x, start, end)Returns the index of the first occurrence of value x in the list. Raises a ValueError if the value is not found.
list.count(x)Returns the number of elements in the list that match value x. Returns 0 if the value is not present.
x in listReturns True if the list contains value x, or False if it does not.
x not in listReturns True if the list does not contain value x, or False if it does.

Sample Code

# Use index() to get the index of an element.
fruits = ["apple", "orange", "grape", "orange", "peach"]
print(fruits.index("orange"))  # 1 (index of the first match)

# Specify a search range (search from index 2 onward).
print(fruits.index("orange", 2))  # 3 (first match at index 2 or later)

# Searching for a value that doesn't exist raises a ValueError.
try:
    fruits.index("strawberry")
except ValueError:
    print("strawberry is not in the list.")

# It is safer to check with the in operator before calling index().
target = "grape"
if target in fruits:
    print(f"Index of {target}: {fruits.index(target)}")

# Use count() to find how many times a value appears.
nums = [1, 2, 2, 3, 2, 4, 5, 2]
print(nums.count(2))   # 4 (2 appears four times)
print(nums.count(9))   # 0 (9 is not present, so 0 is returned)

# A practical example of counting duplicates.
answers = ["A", "B", "A", "C", "B", "A"]
print(f"Chose A: {answers.count('A')}")
print(f"Chose B: {answers.count('B')}")
print(f"Chose C: {answers.count('C')}")

# Use the in operator to check whether an element exists.
shopping = ["milk", "eggs", "bread", "butter"]
print("eggs" in shopping)     # True
print("cheese" in shopping)   # False
print("cheese" not in shopping)  # True

# A typical use in a conditional statement.
if "milk" in shopping:
    print("Milk is in the list.")

# Check whether the list is empty.
if not shopping:
    print("The shopping list is empty.")
else:
    print(f"There are {len(shopping)} items.")

# Check whether all elements satisfy a condition (combined with all and any).
scores = [80, 90, 75, 88]
print(all(s >= 60 for s in scores))  # True (everyone scored 60 or above)
print(any(s >= 90 for s in scores))  # True (at least one person scored 90 or above)

Notes

index() returns the index of the first matching element. If the value does not exist, a ValueError is raised, so it is recommended to check for the value with the in operator first, or handle the exception with a try-except block.

The in operator performs a linear search (O(n)) by comparing each element in order. If you need to search a large dataset frequently, using a set instead of a list allows an average search time of O(1). For data whose primary purpose is lookup, a set or dictionary is more appropriate than a list.

When searching a sorted list, binary search (O(log n)) using Python's standard library bisect module is faster. For sorting and reversing elements, see list.sort() / list.reverse().

If you find any errors or copyright issues, please .