Convert list of 1s and 0s to list of booleans in Python

avatar

Borislav Hadzhiev

Last updated: Aug 28, 2022

banner

Photo from Unsplash

Convert list of 1s and 0s to list of booleans in Python #

To convert a list of 1s and 0s to a list of booleans:

  1. Use a list comprehension to iterate over the list.
  2. Use the bool() class to convert each integer to a boolean.
  3. The new list will only contain boolean values.
main.py
list_of_integers = [1, 0, 1, 0, 1, 1] list_of_booleans = [bool(item) for item in list_of_integers] # 👇️ [True, False, True, False, True, True] print(list_of_booleans)

We used a list comprehension to iterate over the list of integers.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the current integer to the bool() class to convert it to a boolean.

The new list contains the boolean representation of the integers in the original list.

The bool() class takes a value and converts it to a boolean (True or False). If the provided value is falsy or omitted, then bool returns False, otherwise it returns True.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type.
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

The bool() class returns True if passed any non-falsy value.

In other words, passing any integer other than 0 to the bool() class returns True.

Alternatively, you can use the map() function.

Convert list of 1s and 0s to list of booleans using map() #

To convert a list of 1s and 0s to a list of booleans:

  1. Pass the bool() class and the list to the map() function.
  2. The map() function will call the bool() class with each integer in the list.
  3. Use the list() class to convert the map object to a list.
main.py
list_of_integers = [1, 0, 1, 0, 1, 1] list_of_booleans = list(map(bool, list_of_integers)) # # 👇️ [True, False, True, False, True, True] print(list_of_booleans)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The bool() class gets passed each integer in the list and converts each value to a boolean.

Lastly, we used the list() class to convert the map object to a list.

The list class takes an iterable and returns a list object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.