Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map a lambda function to variable that can be a float, int, or list

I’m trying to map a lambda function to variable that can be a float, int, or list.

Test #1, this works:

val = [0.1]
test =  list(map(lambda x: max(x, 1 - x), val))

Test #2, this throws TypeError: 'float' object is not iterable:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val = 0.1
test =  list(map(lambda x: max(x, 1 - x), val))

I tried to solve it with list(val) (that is, list(map(lambda x: max(x, 1 - x), list(val)))), but it throws the same error.

How can I get it to work in both Test #1 and Test #2? Python 3.7

>Solution :

You can handle this case using if condition inside your map function. Try like this:

val = 0.1
test = list(map(lambda x: max(x, 1 - x), val if isinstance(val, list) else [val]))

it will handle your all cases like list, int and decimal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading