Validate if a list has only None elements, strings that only have whitespaces or is empty

Question:


#examples:
lista = ["   ", None, None, "", "  "] #print 'yes!'
lista = [] #print 'yes!'
lista = ["   ", None, None, "", " s"] #print  'no!'
lista = ["sun is bright", "aa", "Hello!"] #print  'no!'

if not any(lista) or all(x in ('', None) for x in lista):
    print("yes")
else:
    print("no")

Considering that the lists that have only strings with empty spaces or have None values, are lists that, although they have information, this information is not really useful, so I needed to create a validation to identify if a list belongs to this type of list with no useful information

I was having trouble putting together a program that prints "yes" if the list[] is empty, has only strings of empty spaces, or has only None elements, and prints "no" otherwise.

What is wrong with my code?

Asked By: Matt095

||

Answers:

Use

if all(not x or not x.strip() for x in lista):

for the check.

not x checks for None and the empty string.

not x.strip() checks for string with whitespace only.

If all gets an empty sequence (or iterator) as argument, it returns True, therefore the empty list will print "Yes".

Answered By: Michael Butscher
lista = ["   ", None, None, "", "  "] #print 'yes!'
# lista = [] #print 'yes!'
# lista = ["   ", None, None, "", " s"] #print  'no!'
# lista = ["sun is bright", "aa", "Hello!"] #print  'no!'

if all(not x or not x.strip() for x in lista):
    print("yes")
else:
    print("no")
Answered By: gour