A.Kruse
A.Kruse

Reputation: 35

Check if any element in list is empty/'not a number' (Python)

I want to use an if-statement that checks if a list contains an empty element. A line that does something like this:

list1 = [1,2,[],2]
list2 = [1,2,1,2]

>>>list1 'contains empty element'
True

>>>list2 'contains empty element'
False

I'm very concerned with run time.

Thanks a lot for any help!

Upvotes: 1

Views: 302

Answers (4)

kederrac
kederrac

Reputation: 17322

you can use:

any(e == [] for e in my_list)

or:

[] in my_list

if you want to use an if-statement:

def check(my_list):
    for e in my_list:
        if e == []:
            return True
    return False

print(check(list1))
print(check(list2))

output:

True
False

Or you can use the ternary operator:

True if [] in my_list else False

Upvotes: 1

Ed Ward
Ed Ward

Reputation: 2331

If you want any number and any element that has a boolean value of True, try this:

def any_empty(lst):
    return not all(isinstance(x, int) or x for x in lst)

print(any_empty([0, 1, 2, 3, ["Foo"]]))
print(any_empty([ () ]))
print(any_empty([ [] ]))

Output:

False
True
True

Upvotes: 1

krishna
krishna

Reputation: 1029

Please check this.

list1 = [1,2,[],2]
list2 = [1,2,1,2]


if [] in list1:
    print("List 1 contains empty list ? ", ([] in list1))

if [] in list2:
    print("List 2 contains empty list ? ", ([] in list2))

Or

print("List 1 contains empty list ? ", ([] in list1))
print("List 2 contains empty list ? ", ([] in list2))

Upvotes: 1

ksha
ksha

Reputation: 2087

Here:

all([not (isinstance(x, list) and not x) for x in list1])

Upvotes: 1

Related Questions