Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check element exists in array

Tags:

python

In PHP there a function called isset() to check if something (like an array index) exists and has a value. How about Python?

I need to use this on arrays because I get "IndexError: list index out of range" sometimes.

I guess I could use try/catching, but that's a last resort.

like image 574
Jonny Avatar asked Dec 20 '11 03:12

Jonny


People also ask

How do you check if an element exists in an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check an element in an array Python?

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.


1 Answers

Look before you leap (LBYL):

if idx < len(array):     array[idx] else:     # handle this 

Easier to ask forgiveness than permission (EAFP):

try:     array[idx] except IndexError:     # handle this 

In Python, EAFP seems to be the popular and preferred style. It is generally more reliable, and avoids an entire class of bugs (time of check vs. time of use). All other things being equal, the try/except version is recommended - don't see it as a "last resort".

This excerpt is from the official docs linked above, endorsing using try/except for flow control:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

like image 118
wim Avatar answered Sep 18 '22 19:09

wim