I have the following output but I want to eliminate the empty lists. How can I do this? It seems that the single quote within the list make it seems like there is something in the list.
[{'Segment': {'Price': 305, 'Mw': 13, '@Number': '1'}}]
[{'Segment': {'Price': 258.43, 'Mw': 46.9, '@Number': '1'}}]
['']
['']
['']
I tried using the code below but it did not work.
if not a:
print "List is empty"
7 Answers 7
Your list is not empty, it has one empty string on it. You can use ''.join
and check as answered:
if not ''.join(a):
do your thing
I guess you can use any
as well on this if your list is sure to have just empty strings.
if any(a):
do your thing
-
I was thinking that, but
any()
also returns True on a truly empty list.gojomo– gojomo05/20/2015 04:17:12Commented May 20, 2015 at 4:17 -
@gojomo Do you mean
any([])
will be True? I thinkall([])
is True and notany
.The problem I see with any is if the list allows other values as [0] etc whereany
is wrong.sagarchalise– sagarchalise05/20/2015 04:20:46Commented May 20, 2015 at 4:20 -
Yep, never mind, I was still thinking in mode of question, trying to trigger on the 'empty-or-filled-with-empties' condition, and had just tested
all()
. Usingany()
to trigger positive action ornot any()
to trigger the nothing-there handling (like discarding the list) should work.gojomo– gojomo05/20/2015 04:24:39Commented May 20, 2015 at 4:24
What you had was a list with a single entry with empty string. It's not an empty list. Best way to check if a list is empty is a correct way to check for empty list.
If you want to check for [''] just do
if a == ['']:
if ''.join(out[0]) != "":
return out
Python counts the empty string as a string. Use a regex if you need to, or merely:
if list[0] != '':
print(list)
Plug that conditional into a For loop as necessary.
-
1what about ls = ['', 1,2,3]James Sapam– James Sapam05/20/2015 04:14:07Commented May 20, 2015 at 4:14
Is this what you want?
old_list=[[{'Segment': {'Price': 305, 'Mw': 13, '@Number': '1'}}],
[{'Segment': {'Price': 258.43, 'Mw': 46.9, '@Number': '1'}}], [''], ['']]
new_list = []
for i in old_list:
if i != ['']:
new_list.append(i)
print new_list
[[{'Segment': {'Price': 305, '@Number': '1', 'Mw': 13}}], [{'Segment': {'Price': 258.43, '@Number': '1', 'Mw': 46.9}}]]
Can i try this way:
>>> def is_empty(ls):
... if all([not len(ls), not ls]):
... print "List is empty"
... else:
... print "List is not empty"
...
>>> is_empty([])
List is empty
>>> is_empty([""])
List is not empty
>>> is_empty([{'Segment': {'Price': 305, 'Mw': 13, '@Number': '1'}}])
List is not empty
>>>
Your list is not empty, it contains an empty string.
If you want to check that your list contains any items that are non-empty you can either use any
:
list = [ '' ]
if any(list):
# List contains non-empty values
or you can filter
it before you use it to remove any empty strings:
list = [ '' ]
list = filter(None, list) # Remove empty values from list
if list:
# List contains items
['']
?