Home > Back-end >  How to map a lambda function to variable that can be a float, int, or list
How to map a lambda function to variable that can be a float, int, or list

Time:10-23

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:

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

CodePudding user response:

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.

CodePudding user response:

You get the error, because in Test #2 val variable is not iterable (because it's a float value), so map() function has no object to iterate through.

The map() function applies a given function to each item of an iterable (list, tuple etc.) and returns an iterator.

Update:

Here is the solution working for both Tests:

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

If the type of val variable is not a list, then we convert it to be a list; otherwise, we leave the val variable without conversion.

Alternatively, you can do it like that (for Test #2):

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