3 ms·
# Instead of doing this if len(numbers) == 0: print("The numbers list is empty") # Many of us do this if not numbers: print("The nu
by Buttons840 5y ago
# Instead of doing this
if len(numbers) == 0:
print("The numbers list is empty")
# Many of us do this
if not numbers:
print("The numbers list is empty")
I tend to write the first form because it is how I think, and I'm writing what I think. "If this list is empty, then..." I suppose a list is only falsy if it is empty. I used to exploit Python's truthyness / falsyness a lot more, but now I like to be more explicit. Ultimately it doesn't matter much, making a single line a tiny bit longer is rarely the most important issue in a project.
- adhocmobility 5y agoThe second case is preferable if numbers is an Optional[List], which is usually the case when passing lists around as arguments. def custom_sum(numbers: Optional[List[int]] = None) -> int: if not numbers: ## something return sum(numbers) This can handle both cases - if numbers is None, or numbers is []
- actually_a_dog 5y agoWouldn't it be easier to say if numbers == []: print ("The numbers list is empty") if your intent is to express "is the list empty?" in the condition?
- sritchie 5y agoThat condition would fail on non-list sequences, like `numbers == (1,2,3)`; the `len` version makes the code more permissive.
- mturmon 5y agoI often use the same if len() construct. It will fail for non-list inputs, which is another reason it can be handy if you want clarify that you’re enforcing a list.
- Buttons840 5y agoAh yes, that's another reason I do it, but I failed to mention. If you see "if not x:" then you're left wondering what x is (a boolean presumably), but "if len(x) == 0:" let's you know you're checking to see if a container is empty.
- dec0dedab0de 5y agoI often use the same if len() construct. It will fail for non-list inputs, which is another reason it can be handy if you want clarify that you’re enforcing a list. len will work for strings, tuples, dicts, sets, plus all kinds of custom classes that implement the __len__ magic method.
- saila 5y agoIf you want to do type-checking, I don't think this a good way to do it. As a sibling comment points out, it doesn't work all that well since many objects respond to `len()`. I think it would be preferable to add type annotations and use mypy to check them or perhaps, in rare circumstances, do an isinstance check.
- mturmon 5y agoAlas, I find this suggestion unpersuasive for the use I have in mind. I get that there would be cases it does apply to. I just want to enforce that the object acts like a list, mainly versus a float, int, or boolean. Tuples are definitely 100% ok, and if someone wants to give me a set, that's almost certainly OK too, in the use cases I'm considering. And so is a numpy vector! Often these objects are held in a container (a dict or class variable), so type annotations would be clumsy as far as I know. Wouldn't I need to create a separate object to enforce the annotation? And the type annotation would need to allow tuples and all flavors of lists or numpy arrays. On the other end of the scale, I don't think either of us wants to use isinstance checks! My primary intent isn't to be bulletproof, it's to show intent. The main fail of using len() in this way is that it accepts strings.
- saila 5y agoI don't see how using len() this way is any different than doing an isinstance check. You're essentially saying, "If this object doesn't respond to len(), raise a TypeError."
- mturmon 5y agoTuple, list, and numpy array are all different isinstance()’s, so I’d have to call them all out. len() avoids that.
- saila 5y agoThis is incorrect, because you can generally do this for sequence types: isinstance(items, Sequence) Or perhaps: isinstance(items, Iterable) # works with numpy arrays Or, equivalent to using len() for type checking, you could do: isinstance(items, Sized)
- tony-allan 5y agoIf you use the technique more generally, you need to watch out for the first case: bool(0) -> False bool(1) -> True bool(str('0')) -> True bool(str('')) -> False bool(None) -> False If you are checking that a variable is set bool(some_var) doesn't work for 0.