I'm new to Python and I'm looking for a standard function that would tell me if an element is present in an array. I found the index
method but it throws an exception if the element is not found. I just need some simple function that would return true
if the element is in the array or false
if not.
Basically an equivalent to PHP in_array
.
To check if an array contains an element or not in Python, use the in operator. The in operator checks whether a specified element is an integral element of a sequence like string, array, list, tuple, etc.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
>>> 1 in [0, 1, 2, 3, 4, 5]
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With