Checking if a List Is Empty
If you come from a statically typed language like Java or C, you might be bothered by the lack of static types in Python. Sure, not knowing the type of a variable can sometimes be frustrating, but there are perks as well. For instance, we can check if a list is empty by its type flexibility.
Python: 3.0    Anurag Rana    11 Jul 2021   1
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
my_list = list()

# Check if a list is empty by its length
if len(my_list) == 0:
    pass  # the list is empty

# Check if a list is empty by direct comparison (only works for lists)
if my_list == []:
    pass  # the list is empty

# Check if a list is empty by its type flexibility **preferred method**
if not my_list:
    pass  # the list is empty
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com