Python List Conversion

Convert a list of 1's and 0's into a list of boolean values while introducing key concepts in Python.

Convert a List of Values

In this tutorial, we review how to convert a list of 1's and 0's into a list of boolean values while introducing several key concepts in Python. There are multiple ways to achieve the conversion in Python. For starters, a for loop with an if/else statement.

integers = [1, 0, 0, 1, 0]  # list of 1's and 0's
booleans = []  # empty list
for value in integers:  # loop over each integer value
    if value == 0:  # check if value is equal to 0
        booleans.append(False)  # append to booleans list
    else:  # fallback condition
        booleans.append(True)  # append to booleans list

The code can be reduced with a ternary operator. In C-style syntax, including a language such as JavaScript, a ternary statement looks like x = some_condition ? true : false with symbols to convey meaning. In Python, the syntax is clearer and reads like a sentence in English e.g. x = True if some_condition else False.

Replace the if/else code block from the for loop example with the ternary operator.

integers = [1, 0, 0, 1, 0]
booleans = []
for value in integers:
    result = False if value == 0 else True  # ternary statement
    booleans.append(result)

An alternative approach to the conditional logic is utilizing a dictionary as a key-value conversion mapper.

integers = [1, 0, 0, 1, 0]
booleans = [] 
mapper = {0: False, 1: True}  # key-value conversion mapper
for value in integers:
    result = mapper[value]  # map the integer to the boolean value
    booleans.append(result) 

Python includes an expression called a list comprehension to concisely create lists. List comprehensions are suitable for creating lists from short and simple loops.

integers = [1, 0, 0, 1, 0]
mapper = {0: False, 1: True}
booleans = [mapper[value] for value in integers]  # list comprehension

Furthermore, Python treats all values as either truthy or falsy, a similar construct found in JavaScript. Integers can be converted into a True/False boolean value using the built-in bool function i.e. bool(0) -> False or bool(1) -> True.

The example code can be further condensed by removing the mapper and converting the integer value into a boolean using the bool function. In effect, a succinct and easily readable implementation with only two lines of code (plus a print statement to view the result).

Loading...
Published