Jul-25-2018, 06:09 AM
(Jul-25-2018, 04:10 AM)Skaperen Wrote: all handles an empty list by returning True, which would be the wrong thing in my current projects.
foo = [] if foo and all(isinstance(x, float) for x in foo): print('all float') else: print('some problem')
Output:some problem
just for completeness - there is also any() - Return True if any element of the iterable is true. If the iterable is empty, return False.also you can 'extend' all() it in your own helper function
def nonempty_alltypes(iterable, check_types): """Check that iterable is not empty and all elements are one of check_types. Returns bool.""" return all((iterable, all(isinstance(x, check_types) for x in iterable))) test_list = [[1,2], [], [1, 3, 'a']] test_for = int for test_item in test_list: print('{} | {} --> {}'.format(test_item, test_for, nonempty_alltypes(test_item, test_for))) test_item = [1, 2, 4.5] test_for = (int, float) print('{} | {} --> {}'.format(test_item, test_for, nonempty_alltypes(test_item, test_for)))
Output:[1, 2] | <class 'int'> --> True
[] | <class 'int'> --> False
[1, 3, 'a'] | <class 'int'> --> False
[1, 2, 4.5] | (<class 'int'>, <class 'float'>) --> True
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs