The preferred way to check if any list, dictionary, set, string or tuple is empty in Python is to simply use an if statement to check it. For example, if we define a function as such:
|
1 2 3 4 5 6 7 |
def is_empty(any_structure): if any_structure: print('Structure is not empty.') return False else: print('Structure is empty.') return True |
It will magically detect if any built in structure is empty. So if we run this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
>>> d = {} # Empty dictionary >>> l = [] # Empty list >>> ms = set() # Empty set >>> s = '' # Empty string >>> t = () # Empty tuple >>> is_empty(d) Structure is empty. True >>> is_empty(l) Structure is empty. True >>> is_empty(ms) Structure is empty. True >>> is_empty(d) Structure is empty. True >>> is_empty(s) Structure is empty. True >>> is_empty(t) Structure is empty. True |
Then, [...]