公告
财富商城
积分规则
提问
发文
2018-12-31 04:46发布
与风俱净
For example, if passed the following:
a = []
How do I check to see if a is empty?
a
You can even try using bool() like this
a = [1,2,3]; print bool(a); # it will return True a = []; print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
Being inspired by @dubiousjim's solution, I propose to use an additional general check of whether is it something iterable
import collections def is_empty(a): return not a and isinstance(a, collections.Iterable)
Note: a string is considered to be iterable. - add and not isinstance(a,(str,unicode)) if you want the empty string to be excluded
and not isinstance(a,(str,unicode))
Test:
>>> is_empty('sss') False >>> is_empty(555) False >>> is_empty(0) False >>> is_empty('') True >>> is_empty([3]) False >>> is_empty([]) True >>> is_empty({}) True >>> is_empty(()) True
len() is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.
len()
JavaScript has a similar notion of truthy/falsy.
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
The truth value of an empty list is False whereas for a non-empty list it is True.
False
True
if not a: print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
最多设置5个标签!
You can even try using bool() like this
I love this way for checking list is empty or not.
Very handy and useful.
Being inspired by @dubiousjim's solution, I propose to use an additional general check of whether is it something iterable
Note: a string is considered to be iterable. - add
and not isinstance(a,(str,unicode))
if you want the empty string to be excludedTest:
len()
is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.JavaScript has a similar notion of truthy/falsy.
a little more practical:
The truth value of an empty list is
False
whereas for a non-empty list it isTrue
.Using the implicit booleanness of the empty list is quite pythonic.