How to know that the list is empty? In some cases, this approach

if len(lst) == 0: return 1 

may cause an error. How to do it right?

  • 3
    Normal if not lst: not suitable? - Vladimir Gamalyan
  • Um, can you give an example of such an error? If lst is really a list and is really empty, then this code should work, but you probably do something wrong with the variable itself. - andreymal
  • @andreymal can topicaster worry that someone will write def len(a): return 1 ? - Vladimir Gamalyan
  • @VladimirGamalian in this case there are a lot of more serious reasons for concern: D - andreymal
  • @andreymal is yes). For junior by the way, not such a hypothetical situation. For example, using built-in file names for their variables is quite common. - Vladimir Gamalyan

1 answer 1

Unlike some programming languages, in Python an object is considered false only if it is empty. This means that you do not need to check the length of a string, tuple, or dictionary — it suffices to check it as a logical expression.

Taken from here , you can find something else useful.

Therefore, the @Vladimir Gamalian version proposed in the commentary is appropriate:

 if not lst: