Truthiness
String Truthiness
Booleans are not the only value that can go in an if statement condition. Python has a concept of truthiness that is greater than just True and False.
Let’s try out truthiness on strings.
>>> word = "bird"
>>> if word:
... print("word is truthy")
...
word is truthy
>>> word = ""
>>> if word:
... print("word is truthy")
...
Strings evaluate as truthy if they contain text. They are falsey if they do not.
>>> number = 1000
>>> if number:
... print("number is truthy")
...
number is truthy
>>> number = 0
>>> if number:
... print("number is truthy")
...
Numbers are truthy if they are non-zero and falsey if they are zero.
Truthiness is not the same thing as boolean True or False. For example, a number that is truthy is not True. Truthiness can be determined by using the bool constructor to convert a value to a boolean:
>>> bool("")
False
>>> bool("hello")
True
>>> bool(0)
False
>>> bool(-1)
True
List Truthiness
Lists evaluate to falsey if they are empty and truthy otherwise:
>>> numbers = []
>>> if numbers:
... print("Non-empty")
...
>>> numbers.append(5)
>>> numbers
[5]
>>> if numbers:
... print("Non-empty")
...
Non-empty
A list containing only the value “None” is still truthy because it contains an element:
>>> numbers = []
>>> numbers.append(None)
>>> if numbers:
... print("Non-empty")
...
Non-empty
Tuple Truthiness
Tuples evaluate to falsey if they are empty and truthy otherwise:
>>> numbers = ()
>>> if numbers:
... print("Non-empty")
...
>>> if not numbers:
... print("empty")
...
empty
An empty tuple is falsey:
>>> bool(())
False
And a non-empty tuple is truthy:
>>> bool((1,))
True
Dictionary Truthiness
Like lists, tuples, and strings, dictionaries are also falsey when empty and truthy when non-empty:
>>> bool({})
False
>>> bool({1: 2})
True