7

Suppose I have a list ['', 'Tom', 'Jane', 'John', '0'], and I wrote the following to check if it has empty string '':

if any('' in s for s in row[1:]):
        print "contains empty string, continue now"
        continue

I expect this to only pick the empty string, but this also picks a list that contains '0'. The '0' string is valid and I do not want to filter it out. So how can I check for an empty string in a python list?

1
  • '' in s -> s == '' (or more trivially if '' in row) Commented May 22, 2014 at 18:15

5 Answers 5

14

You can just check if there is the element '' in the list:

if '' in lst:
     # ...

if '' in lst[:1]:  # for your example
     # ...

Here is an example:

>>> lst = ['John', '', 'Foo', '0']
>>> lst2 = ['John', 'Bar', '0']
>>> '' in lst
True
>>> '' in lst2
False
Sign up to request clarification or add additional context in comments.

Comments

4
any('' in s for s in row[1:])

checks, for each string s in the list row[1:], whether the empty string is a substring of it. That's always true, trivially. What you mean is

any(s == '' for s in row[1:])

But this can be abbreviated to

'' in row[1:]

Comments

4

Instead of using:

if any('' in s for s in row[1:]):

change your condition to:

if '' in your_list:

where your_list is name of list you are examining.

Comments

3

Let's take your example and give the list a name:

list = ['', 'Tom', 'Jane', 'John', '0']
if '' in list:
    do something

That is all you need!

Comments

1

How about this:

if any(len(x) == 0 for x in row):
    print("contains empty string, continue now")
    continue

2 Comments

This can give false positives if some elements of row are not strings.
I must add that my answer gives a false positive if row is a string, so whether that's enough of a problem to give a downvote is questionable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.