Search code examples
pythonlistinteger

Absolute vaule of an input of a list of integers using map() function


Usually, when I have to input a list of space-separated integers in this fashion:

12 15 31 -12

I use this function:

list(map(int, input().split()))

So that it returns [12, 15, 31, -12].

But, now, if for some reason I have to input the numbers as positive integers only (ie. their absoulte value), how should I go with it the easiest way?
I could very well input all the numbers in the list and then one by one, convert them to their absolute value, but is their a better method?


Solution

  • This is trivial once you understand what the map(func, iterable) function does: it calls the function func on each element of the given iterable, and returns an iterator containing the results. It's equivalent to doing this:

    def my_map(func, iterable):
        for item in iterable:
            yield func(item)
    

    So how do you get the absolute integer value? Change what func does!

    1. Define a function and map to that:
    def absint(x):
        return abs(int(x))
    
    list(map(absint, input().split()))
    
    1. Define a lambda function that calls abs and int:
    list(map(lambda x: abs(int(x)), input().split()))
    

    1 and 2 are essentially the same, I don't expect there to be any difference in performance between the two.