I would like to know what would be the best way to check if a list is empty.
I know this question seems silly, but I realize that sometimes when you are working with others and others read your code, using certain functions may look better than others, and would be more understandable for people coming from different programming languages.
Say I have a list:
names = ["Bob", "Billy", "Samuel", "Adam", "Rob"]
This is one way I can check if the list is empty:
is_empty = bool(names)
This is another:
is_empty = any(names)
I do realize the any function checks if there is at least 1 true value inside a list. What would be the best and quickest way to check if the list is empty? Which would look the best and in which scenarios? Are there any faster ways that I do not know of?
is_empty = (names == [])
? – Scott Hunter Nov 18 '20 at 0:57len(names) == 0
is what seems most readable to me. – Telmo Trooper Nov 18 '20 at 0:59any(names)
doesn't work to check if it's empty. – Aplet123 Nov 18 '20 at 1:00any
won't work here.any
doesn't check for "any elements in the list", it checks for "any truthy elements in the list". – Carcigenicate Nov 18 '20 at 1:05