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.
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.
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.
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.
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