hello1212 hello1212 - 1 year ago 103
Python Question

What is Truthy and Falsy in python ? How is it different from True and False?

I just came to know there are Truthy and Falsy values in python which are different from the normal


Can someone please explain in depth what truthy and falsy values are?
Where should I use them?
What is the difference between truthy and
values and falsy and
values ?

Answer Source

As the comments described, it just refers to values which are evaluated to True or False.

For instance, to see if a list is empty, instead of checking like this:

if len(my_list) != 0:
   print "Not empty!"

You can simply do this:

if my_list:
   print "Not empty!"

This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.

Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.

The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like this, and those which are considered False.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download