python - How do I check if the list contains empty elements? -
suppose have empty string, split:
>>>''.split(',') ['']
the result of split ['']
. use bool
check whether or not it's empty. return true
.
>>>bool(['']) true
how check split result empty?
with bool([''])
you're checking if list ['']
has contents, which does, contents happen empty string ''
.
if want check whether all elements in list aren't 'empty' (so if list contains string ''
return false
) can use built-in function all()
:
all(v v in l)
this takes every element v
in list l
, checks if has true
value; if all elements returns true
if @ least 1 doesn't returns false
. example:
l = ''.split(',') all(v v in l) out[75]: false
you can substitute any()
perform partial check , see if any of items in list l
have value of true
.
a more comprehensive example* both uses:
l = [1, 2, 3, ''] all(l) # '' doesn't have true value out[82]: false # 1, 2, 3 have true value any(l) out[83]: true
*as @shadowranger pointed out in comments, same exact thing can done all(l)
or any(l)
since both accept iterable in end.
Comments
Post a Comment