jeudi 20 septembre 2018

python if statement on empty list [duplicate]

This question already has an answer here:

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?

Aucun commentaire:

Enregistrer un commentaire