by kstrauser · 3y ago · 0 comments
users = database.fetch_users()
if not users:
print("Didn't find anyone.")
and name = input()
if not name:
print("You didn't enter a name.")
Of course you could work around those like `if len(users) == 0` or `if not len(users)` or `if name != ""`, but each of those is uglier.`if not users` translates very nicely to English: "if there are not any users...". I'm glad Python defined `bool(list)` that way.
if my_container.empty():
# do stuff
than if not my_container:
# do stuff
The second implementation behaves the same if either my_container is None or if my_container is empty (or if my_container is 0 or ""...), whereas the first implementation allows me to handle those cases differently. The first implementation is also more explicit and easier to understand on a first read.It's also easier to debug. Is users supposed to be None in your example? Possibly, but your code doesn't give me any hints. Is my_container supposed to be None in my example? Probably not based on the way I explicitly used the .empty() method.
Really, though, list.empty() is canonically spelled “not list” in Python. That’s the idiom to learn, read, and write.