-4

I found this article about python boolean at boolean. I was wondering why an empty array, string and the number 0 is false while the other ones are not. Can someone explain this to me? And do note: this is not a duplicate of another article.

Jadon Jung
  • 27
  • 1
  • 1
  • 12

2 Answers2

0

Values in python can be either truthy or falsy.

"", [], 0 are all falsy values.

When there is a value of some kind, it is considered truthy.

They are not the same as true and false but when used as a conditional by themselves they are treated as such.

A lot of programming languages have this concept.

This is just the simple explanation, the answers on this question What is Truthy and Falsy? How is it different from True and False? are far more detailed.

0

This is for easy checking of whether an object has data.

def some_func(some_string: str):
    if some_string:  # both an empty string and None eval to false
        # do something with string

If you are wondering why it works, the string and list object have an overloaded __bool__ special function.

State
  • 1
  • 2
  • 2