Validation element exists in array

PHP has a function called isset() to check if something exists (like an array index) and it matters. What about python?

I need to use this on arrays because sometimes it changes the index IndexError: list out of range.

I think I could use try / catching, but this is the last resort.

+54
python
Dec 20 2018-11-11T00:
source share
5 answers

Look before you jump ( LBYL ):

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

It’s easier to ask forgiveness than permission ( EAFP ):

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

In Python, EAFP seems to be a popular and preferred style (because it is generally more reliable). Thus, ceteris paribus, I recommend that you use the try / except version of the version in this case - do not consider it as a "last resort".

This snippet is taken from the official docs linked above endorsing the use of try / other than flow control:

This general Python coding style assumes valid keys or attributes and catches exceptions if the assumption is false. This clean and fast style is characterized by the presence of many attempts, besides applications.

+90
Dec 20 '11 at 4:08
source share

EAFP vs LBYL

I understand your dilemma, but Python is not PHP and the coding style known as Easier to apologize than for resolving (or EAFP ) the general coding style in Python .

See source (from documentation ):

EAFP - It's easier to ask forgiveness than permission. This general Python coding style assumes valid keys or attributes and throws exceptions if the assumption is false. This clean and fast style is characterized by many attempts and exceptions. This method contrasts with the LBYL standard common to many other languages, such as C.

So, basically, using try-catch statements here is not a last resort; this is a common practice .

Arrays in Python

PHP has associative and non-associative arrays, Python has lists, tuples, and dictionaries. Lists are similar to non-associative arrays of PHP, dictionaries are similar to associative arrays of PHP.

If you want to check if the "key" exists in the "array", you must first indicate what type it is in Python, because they throw different errors when the "key" is missing:

 >>> l = [1,2,3] >>> l[4] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> l[4] IndexError: list index out of range >>> d = {0: '1', 1: '2', 2: '3'} >>> d[4] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> d[4] KeyError: 4 

And if you use the EAFP coding style, you should just catch these errors appropriately.

LBYL Coding Style - Checking for Indexes

If you insist on using the LBYL approach, these are the solutions for you:

  • for lists, just check the length, and if possible_index < len(your_list) , then your_list[possible_index] exists, otherwise it is not:

     >>> your_list = [0, 1, 2, 3] >>> 1 < len(your_list) # index exist True >>> 4 < len(your_list) # index does not exist False 
  • for dictionaries, you can use the in keyword, and if possible_index in your_dict , then your_dict[possible_index] exists, otherwise it is not:

     >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3} >>> 1 in your_dict # index exists True >>> 4 in your_dict # index does not exist False 

Did it help?

+41
Dec 20 2018-11-12T00:
source share
 `e` in ['a', 'b', 'c'] # evaluates as False `b` in ['a', 'b', 'c'] # evaluates as True 

EDIT : clarifying new answer:

Note that PHP arrays are significantly different from Python, combining arrays and dicts into one intricate structure. Python arrays always have indices from 0 to len(arr) - 1 , so you can check if your index is in this range. try/catch is a good way to do this pythonically.

If you are asking about the hash functionality of PHP arrays (Python dict ), then my previous answer still looks like this:

 `baz` in {'foo': 17, 'bar': 19} # evaluates as False `foo` in {'foo': 17, 'bar': 19} # evaluates as True 
+15
Dec 20 2018-11-11T00:
source share

has_key is fast and efficient.

Use an hash instead of an array:

 valueTo1={"a","b","c"} if valueTo1.has_key("a"): print "Found key in dictionary" 
+7
Dec 24 '13 at 15:45
source share

You can use the built-in dir() function to create similar behavior for PHP isset() , something like:

 if 'foo' in dir(): # returns False, foo is not defined yet. pass foo = 'b' if 'foo' in dir(): # returns True, foo is now defined and in scope. pass 

dir() returns a list of names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir .

0
Dec 20 '11 at 4:15
source share



All Articles