Reputation: 811
Please consider this snippet:
>>> i = ["", 1, 2]
>>> all([x for x in i])
False
What would be Pythonic way to make this snippet return True
even if item in iterable is empty string?
Standard restrictions should apply - if item is None
or False
etc, it should return False as expected.
Upvotes: 0
Views: 229
Reputation: 9863
You can use all, for instance:
tests = [
[None, False, "", 1, 2],
["", 1, 2],
[1, 2],
[]
]
for i in tests:
print i
print all(filter(lambda x: x != '', i))
print all(True if x == '' else x for x in i)
print '-' * 80
Upvotes: -1
Reputation: 18467
all([x for x in i if not isinstance(x, str)])
The only falsy string is the empty string, so if you don't want to test for it, then filter out the strings.
Upvotes: 1
Reputation: 107347
>>> lst = ["", 1, 2]
>>>
>>> all(True if i=='' else i for i in lst)
True
If you want True if there is at least one item that evaluates to True use any()
.
>>> any(lst)
True
Note that in general any()
and all()
accept iterable argument and you don't need to loop over them.
Upvotes: 2