Reputation: 161
I'm looking to create a function that returns a list of True and False, from a one value integer compared with a list of integers and I can't figure out how to return the list of True, False from the function.
TIA
Here is my code:
num = 7
numListLength = [7, 7, 0]
def compareList():
for num in numListLength:
if num == numListLength:
return True
else:
return False
print(compareList())
the result I want is a list like this:
[True, True, False]
Upvotes: 0
Views: 786
Reputation: 662
You can use map
operator and then give a function to compare the numbers of items with the number.
num = 7
numListLength = [7, 7, 0]
result = list(map(lambda a: a == num, numListLength))
print(result)
will give result [True, True, False]
Upvotes: 0
Reputation: 487
A bit step-to-step piece of code you can find below, with a correction. Also please take a note that your if statement was not entirely correct, and that you've mixed usage of variable n. Example follows:
num = 7
numListLength = [7, 7, 0]
def compareList():
global numListLength
results = []
for val in numListLength:
if val == num:
results.append(True)
else:
results.append(False)
return results
print(compareList())
Upvotes: 1
Reputation: 82775
Using a list comprehension
Ex:
num = 7
numListLength = [7, 7, 0]
def compareList():
return [number == num for number in numListLength]
print(compareList())
# --> [True, True, False]
Note: In your solution you are returning the value after the first comparison instead you can append the comparison result to a list and return that.
Upvotes: 1