5 Best Ways to Check if a Number Is in an Array in Python

πŸ’‘ Problem Formulation: Python developers often come across the need to determine whether a particular number is present in an array. This article tackles the problem by illustrating how to check if a number, say 42, is included in an array like [34, 67, 42, 90, 10]. The desired output for this problem is a Boolean value: True if 42 is in the array, or False otherwise.

Method 1: Using the ‘in’ Keyword

The ‘in’ keyword in Python is a straightforward way to check for the presence of an element in a list. It evaluates to True if the specified element is found in the sequence and False if not. This method is not only idiomatic and easy to read but also efficient for searching small to moderately sized lists.

Here’s an example:

numbers = [34, 67, 42, 90, 10]
num_to_check = 42
is_present = num_to_check in numbers
print(is_present)

Output: True

This snippet initializes an array named numbers and uses the in keyword to evaluate the presence of num_to_check within it. Then it prints the result, which verifies if num_to_check is indeed in the array.

Method 2: Using the list.index() Function

The list method index() checks for the presence of an element and returns its index if found. If the element is not present, it throws a ValueError. This method can not only check the presence of an element but also find its position in the list.

Here’s an example:

numbers = [34, 67, 42, 90, 10]
num_to_check = 42
try:
    index_position = numbers.index(num_to_check)
    print("Found at index:", index_position)
except ValueError:
    print("Not in list")

Output: Found at index: 2

Using a try-except block, the code attempts to find the index of num_to_check in the array numbers. If found, it prints the index; if not, it catches the ValueError and informs that the number is not in the list.

Method 3: Using the list.count() Method

The count() method in a list returns the number of occurrences of an element in the list. It is useful for scenarios where you want to know how many times a number appears in an array.

Here’s an example:

numbers = [34, 67, 42, 90, 10, 42]
num_to_check = 42
count = numbers.count(num_to_check)
print(count > 0)

Output: True

The code uses list.count() to count how many times num_to_check appears in numbers and checks whether this count is greater than zero, confirming the presence of the number.

Method 4: Using a Loop

Though less Pythonic, iterating over the array with a loop allows you to check for an element’s presence while also implementing additional logic if needed.

Here’s an example:

numbers = [34, 67, 42, 90, 10]
num_to_check = 42
found = False

for num in numbers:
    if num == num_to_check:
        found = True
        break
    
print(found)

Output: True

This code iterates through each element in numbers and checks if it is equal to num_to_check. The loop breaks as soon as a match is found to avoid unnecessary iterations, and the result is printed.

Bonus One-Liner Method 5: Using any() Function

The any() function checks if any element in an iterable evaluates to True. It’s concise and can immediately stop evaluating once it finds any element that meets the condition, making it efficient.

Here’s an example:

numbers = [34, 67, 42, 90, 10]
num_to_check = 42
print(any(num == num_to_check for num in numbers))

Output: True

By using a generator expression, this one-liner checks each element to see if it equals num_to_check and returns True immediately when a match is found.

Summary/Discussion

  • Method 1: The ‘in’ Keyword. Simple and idiomatic. Best for small to moderate lists but may be less efficient for very large lists.
  • Method 2: Using list.index(). Allows finding the index of an element. It requires handling an exception, which may add unnecessary overhead for just checking presence.
  • Method 3: Using list.count(). Useful for counting elements but overkill if you just need to confirm presence.
  • Method 4: Using a Loop. Offers flexibility for additional checks but is less concise and not as Pythonic as other methods.
  • Bonus Method 5: Using any() Function. Concise, efficient for large lists due to short-circuiting. However, it might be less readable to those unfamiliar with generator expressions.