Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the list contains empty elements?

Suppose I have a empty string, it will be split:

>>>''.split(',')
['']

The result of the split is ['']. I use bool to check it whether or not it's empty. It will return True.

>>>bool([''])
True

How do I check the split result is empty?

like image 431
Tony Avatar asked Feb 03 '16 03:02

Tony


People also ask

How do you check if a list has an empty element?

An empty list is a list with no elements ( len(l) == 0 ). Consider this would be true: l = [""]; l[0] == "" as would l = [None]; l[0] is None .

How do you check if a list has an empty string?

Example 2: Using the len() Function Then we used if statement to check if the length of the list is equals to zero or not. If the condition sets to be true then the string is empty. Otherwise the string is not empty.

How do you check if a list is empty or null?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.

How do you check if a list space is empty in Python?

Python isspace() method is used to check space in the string. It returna true if there are only whitespace characters in the string.


3 Answers

With bool(['']) you're checking if the list [''] has any contents, which it does, the contents just happen to be the empty string ''.

If you want to check whether all the elements in the list aren't 'empty' (so if the list contains the string '' it will return False) you can use the built-in function all():

all(v for v in l)

This takes every element v in list l and checks if it has a True value; if all elements do it returns True if at least one doesn't it returns False. As an example:

l = ''.split(',')

all(v for v in l)
Out[75]: False

You can substitute this with any() to perform a partial check and see if any of the items in the list l have a value of True.

A more comprehensive example* with both uses:

l = [1, 2, 3, '']

all(l)
# '' doesn't have a True value
Out[82]: False

# 1, 2, 3 have a True value
any(l)
Out[83]: True

*As @ShadowRanger pointed out in the comments, the same exact thing can be done with all(l) or any(l) since they both just accept an iterable in the end.

like image 102
Dimitris Fasarakis Hilliard Avatar answered Oct 17 '22 07:10

Dimitris Fasarakis Hilliard


If emptiness is the important result, probably best to test the original string first:

x = ''
if x:
    # Original string was non-empty, split it
    splitx = x.split(',')
    if any(splitx):
        # There was at least one character in the original string that wasn't a comma

The first test rules out empty initial strings, the second one using any rules out strings that were nothing but the split character, and therefore returned a whole bunch of empty strings, but no non-empty strings. As long as you got one non-empty string, it passes.

Note: In case you're trying to parse CSV files, don't use .split(','); there is a csv module that handles this correctly (including escapes, quoting, etc.), and should ALWAYS be used for parsing CSV, never roll your own parser. Added bonus: csv will convert '' inputs to [] rows, which you can test for truthiness directly, not to [''] like str.split does. Example:

>>> import csv, io

>>> f = io.StringIO('\n\na,b,c\n1,2,3\n\n')
>>> [row for row in csv.reader(f) if row]  # Stripping easily
[['a', 'b', 'c'], ['1', '2', '3']]

vs. the same approach with str.split(',') which still doesn't handle quoting, escaping, etc.:

>>> f = io.StringIO('\n\na,b,c\n1,2,3\n\n')
>>> stripped = (line.rstrip('\r\n') for line in f)  # Must manually strip line endings first
>>> [line.split(',') for line in stripped if line]
[['a', 'b', 'c'], ['1', '2', '3']]
like image 2
ShadowRanger Avatar answered Oct 17 '22 07:10

ShadowRanger


The split result isn't empty. The sense of "emptiness" you're looking for is best checked by looking at the original, unsplit string:

if not original_string:
    # It's empty.

But if you really want to look at the split result for this:

if len(split_result) == 1 and not split_result[0]:
    # It's "empty".
like image 1
user2357112 supports Monica Avatar answered Oct 17 '22 09:10

user2357112 supports Monica