How to search for a value in a Python array?

In Python, you can use either of the following methods to find a value in an array:

Option 1: Method 1: Utilize the “in” operator.

You can use the “in” operator to check if a value is in an array. It will return True if the value exists in the array and False if it does not.

arr = [1, 2, 3, 4, 5]
value = 3

if value in arr:
    print("值存在于数组中")
else:
    print("值不存在于数组中")

Output:

值存在于数组中

Option 2: Utilizing the index() method

You can use the index() method to get the index of a value in an array. If the value exists in the array, it will return the first occurrence of its index; if the value does not exist in the array, it will raise a ValueError exception.

arr = [1, 2, 3, 4, 5]
value = 3

try:
    index = arr.index(value)
    print("值出现在索引", index)
except ValueError:
    print("值不存在于数组中")

Output:

值出现在索引 2

Please note that if a value appears multiple times in an array, the index() method will only return the index of its first occurrence. If you want to get all occurrence indexes, you can use a loop to iterate through the array and compare each element.

bannerAds