0

The python if statement can be used in the following way

a = []
if a:
    # do something

i.e., the conditional can be an object (in this case a list). In this case, as far as I understand it, the conditional is evaluated by bool([]) which evaluates to False. On the other hand, bool([1]) evaluates to True and hence something is done.

I personally like this behaviour - it seems clear, but colleagues have pointed out it is unclear.

Is this recommended? What are the potential gotcha's? Is it pythonic or should something more explicit be done?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Greg
  • 11,654
  • 3
  • 44
  • 50
  • have a look at this: https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty – Dani Mesejo Sep 21 '18 at 00:49
  • 1
    The type of `a` is generally not guaranteed when it's evaluated like that. Using an if like that is generally the most pythonic way because it can handle any input. On the other hand, everything is context dependent and asking for general opinions like this will just mess you up in the long run. – Mad Physicist Sep 21 '18 at 00:51
  • 1
    One minor annoyance I have encountered with this idiom is that some times users use list and Numpy arrays interchangeably and this breaks when `a` is a Numpy array with more than 1 element. – lightalchemist Sep 21 '18 at 00:52
  • Wait...I didn't mark this as a duplicate. It is not a duplicate of what's been listed. I marked it as opinion based. Don't lie about me, SO! – Matt Messersmith Sep 21 '18 at 00:56
  • Hi All, thanks for the input. Agreed it is opinion-based. But, this is not a duplicate of that question. – Greg Sep 21 '18 at 01:03

0 Answers0