w3resource

Python: bool() function

bool() function

The bool() function is used to convert a value to a Boolean.

Syntax:

class bool([x])
Python: Built-in function - bool function()

Version:

(Python 3.2.5)

If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

Return value:

Boolean Values (True/False).

Example: Python bool() function

val = True
print("val = ", bool(val))
val = False 
print("val = ", bool(val))
val = 5
print("val = ", bool(val))
val = 0
print("val = ", bool(val))
val = bool()
print("val = ", bool(val))

Output:

val =  True
val =  False
val =  True
val =  False
val =  False

Check if a list is empty or not ?

l = []
if not l:
    print("List is empty.")
else:
    print("List is not empty.")
l = [1, 2, 3]
if not l:
    print("List is empty.")
else:
    print("List is not empty.")

Output:

List is empty.
List is not empty.

Python Code Editor:

Previous: bin()
Next: bytearray()

Test your Python skills with w3resource's quiz



Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9