I'm translating a Python code to C in order to take advantage of the parallelism available on HPC systems. The original programmer used a conditional in Python that confuses me:
if rnum <> current_res:
alim = 0
if len(f): alim = f[-1]
What does if len(f) satisfy? I cannot find this convention used in this way anywhere online. I imagine it is a bad programming practice.
3 Answers 3
In Python, values that are considered 'empty', such as numeric 0, are considered False in a boolean context, and otherwise are True.
Thus, len(f) is True if f has length, otherwise it is False. If f is a standard Python sequence type then the code can be simplified to:
if f: alim = f[-1]
because the same applies to sequences; empty is False, having a non-zero length means it's True *.
See Truth Value Testing in the Python documentation for all the important details.
Note that <> has been deprecated; you should really use != instead.
*: Note that doesn't necessarily apply to non-builtin sequence types, only those that implement __bool__ in this way.
5 Comments
len(f) holds the same truth value as f? Surely it depends on ff implements a custom __nonzero__ (__bool__ py3k) then they could be different, but that's a rare case.f is a class I created and I override len to return 4... it won't be the same. But then again I should be beaten with a stick if I did.__nonzero__ it will be the same.In most cases if len(f): will be the same thing as if f:...
the reason is because if f has no length, it will return 0 which is a falsy value. Actually, truth testing actually checks the length of an object (__len__) under some circumstances.
Comments
This
if len(f)
would translate to:
if len(f) != 0
or in this case, since len(f) is never negative,
if len(f) > 0
10 Comments
!= 0, but since you can't have a negative length sequence, it's not functionally relevant.len, and I included it because len > 0 is more readable.integer >= 0, but I don't know that means that it's enforced or just expected...if f:.len > 0 is the best option :P
<>has long since been deprecated. Use!=instead.