How to Convert a List of Booleans to Integers

Problem Formulation and Solution Overview

In this article, you’ll learn how to convert a List of Booleans to Integers.

In Python, the Boolean is a built-in data type. These values represent True (1) or False (0). Also referred to as Truthy or Falsy values. In this article, we will articulate how these values behave.

To make it more fun, we have the following running scenario:

Ms. Darnell, a Math Teacher at Dion Junior High, has given her class a Math exam based on True/False answers. Each student’s results return to her as a List of Boolean values.


πŸ’¬ Question: How would we write code to convert a List of Boolean values to Integers?

We can accomplish this task by one of the following options:


Method 1: Use List Comprehension

This method uses List Comprehension to loop through a List of Boolean values and converts them from a True/False Boolean value to an integer representation of 1 or 0.

student_exam = [True, False, True, True, True, True, True, False, True, True]
student_tally = [int(x) for x in student_exam]
print(student_tally)

Above, declares a List of True/False values based on a single student’s results from the Math exam. These results save to student_exam.

Next, List Comprehension is used to loop through and examine each element of student_exam (a Boolean List) and assign an integer value of one (1) for True and zero (0) for False. These results are saved to student_tally and output to the terminal.

[1, 0, 1, 1, 1, 1, 1, 0, 1, 1]

How can we retrieve the actual grade?

student_grade = sum(x for x in student_tally if x == 1)
print(student_grade)

Above uses Python’s built-in sum() function and passes one (1) argument, student_tally to loop through and calculate the number of times the integer value one (1) is found.

This result saves to student_grade and is output to the terminal.

8

Method 2: Use map() and list()

This method uses map() in conjunction with a list to convert a List of Boolean to Integers.

student_exam = [True, False, True, True, True, True, True, False, True, True]
student_tally = list(map(int, student_exam))
print(student_tally)

Above, declares a List of True/False values based on a single student’s results from the Math exam. These results save to student_exam.

Next, student_exam is converted to a map() object. If output to the terminal at this point, the output would be similar to below:

<map object at 0x000001C4D34DB550>

This object is then converted to a list and saved to student_tally.

[1, 0, 1, 1, 1, 1, 1, 0, 1, 1]

πŸ’‘Note: To retrieve the actual grade, call the sum() function used in Method 1.


Method 3: Use NumPy multiply()

This method imports the NumPy library and uses multiply() function to convert a List of Boolean values to Integers.

To run this example error-free, the NumPy library must be installed and imported. Click here for installation instructions.

import numpy as np 
student_exam = np.array([True, False, True, True, True, True, True, False, True, True])
student_tally = np.multiply(student_exam, 1)
print(student_tally)

Above, imports the NumPy library.

Next, numpy.array() is called and passed a List (array) of Booleans. This saves to student_exam.

Next, numpy.multiply() is passed two (2) arguments: a List of Boolean values (student_exam) and a number to multiply each element with (1). This operation executes, saves to student_tally and is output to the terminal.

[1 0 1 1 1 1 1 0 1 1]

How can we retrieve the actual grade using NumPy?

student_grade = np.sum(student_tally)  
print(student_grade)

Above, uses NumPy’s sum() function and passes one argument, student_tally. The True values (1) are calculated and output to the terminal.

8

Method 4: Use a Pandas DataFrame

This method creates a Pandas DataFrame from a List of Booleans and converts them to Integers.

To run this example error-free, the Pandas library must be installed and imported. Click here for installation instructions.

import pandas as pd 
student_exam = [True, False, True, True, True, True, True, False, True, True]
df = pd.DataFrame(student_exam, columns=['Exam_Results'])
df['Exam_Results'] = df['Exam_Results'].astype(int)
print(df)

Above, imports the Pandas library.

Next, a List of True/False values is declared based on a single student’s results from the Math exam. These results save to student_exam.

The following line passes a DataFrame with two (2) arguments, the List created earlier (student_exam) and a column name (‘Exam Results‘). Then a DataFrame is created and the results save to df.

The next line converts the True/False values in the original column to Integer values, saves back to the original column df['Exam_Results'] and output to the terminal.

Exam Results
0
1
2
3
4
5
6
7
8
9
1
0
1
1
1
1
1
0
1
1

How can we retrieve the actual grade using a Pandas DataFrame?

student_grade = df['Exam_Results'].sum()
print(student_grade)

Above, uses Pandas sum() function to calculate the grade and output to the terminal.

8

Summary

These methods of converting a List of Booleans to Integers should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Regex Humor

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee. (source)