Increasing expressiveness in the test of array elements

I like Python for its expressiveness. I cannot express everything as compactly as I would like. For example, I write quite often:

def is_everything_okay(some_array): for s in some_array: if not is_okay(s): return False return True 

But this is more Java than Python. How to improve the expressiveness (and probably speed of execution) of this piece of code?

+4
source share
2 answers

Use the built-in all() function:

 all(is_okay(s) for s in some_array) 
+5
source

Just to fill it in Sven answer * ... docs for 2.7: http://docs.python.org/library/functions.html#all

all(iterable)
Return True if all elements of the iterable are true (or if the iterability is empty).

Equivalent:

 def all(iterable): for element in iterable: if not element: return False return True 

An almost exact copy of the code you are showing ...

So, using form awareness (is_okay(s) for s in some_array) creates an iterability that is parsed by all()

Without special testing, you will not know which is faster.

  • and because I'm trying to complete a Python class, I take and have to answer some questions!
0
source

Source: https://habr.com/ru/post/1395320/


All Articles