Home > Back-end >  How to covert a list of values into boolean true false
How to covert a list of values into boolean true false

Time:12-20

I am new to python and wanted to see if I could get some help on how I can convert a list of values into booleans.

I have a list:

lst = [-10.4, -33.6, -1.2, -11.4, -1.1] 

I am trying to define a function that will go through lst and assign True if the number is equal to or less than -10, and False if the number is greater than -10.

Expected output:

lst: [True, True, False, True, False]

Down below is the code I attempted to write but didn't retrieve the results I wanted:

def covert_to_boolean(lst):
    for num in lst:
        if num >= -10: 
            return True
    else: 
        False 
        return lst

Input:

covert_to_boolean(list_1)

Output:

True

CodePudding user response:

lst = [-10.4, -33.6, -1.2, -11.4, -1.1]

out=[i<=-10 for i in lst]

print(out)
#[True, True, False, True, False]

CodePudding user response:

def covert_to_boolean(lst):
    return_list = []
    for _, num in enumerate(lst):
        if num >= -10: 
            return_list.append(True)
    else: 
        return_list.append(False)
    return return_list

CodePudding user response:

Loop through the list like for num in range(len(lst)) and with the same if condition, just set lst[num] = True or lst[num] = False

it would look like the following

for num in range(len(lst)):
    if lst[num] >= -10:
        lst[num] = True
    else:
        lst[num] = False

CodePudding user response:

You can also use map():

list_1 = [-10.4, -33.6, -1.2, -11.4, -1.1]

def covert_to_boolean(lst):
    return [*map(lambda i:i<=-10,lst)]

print(covert_to_boolean(list_1))

# [True, True, False, True, False]
  • Related