map function in Python is a convenient way to execute function for a collection. Let’s see an example that does not use map function.
class playground(unittest.TestCase): def pow(self, n): return n**n def test_pow(self): numbers = range(10) for number in numbers: result = self.pow(number) print(result)
1 1 4 27 256 3125 46656 823543 16777216 387420489
The example above just executes the pow function sequentially for every item in the integer list.
If you use a map function, the code becomes concise and easier to manage. It might be a little confusing but if you get used to it, it’s not too bad.
class playground(unittest.TestCase): def pow(self, n): return n**n def test_map(self): numbers = range(10) results = map(self.pow, numbers) print(list(results))
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]
I didn’t know 0^0 was 1… I knew n^0 was always 1 but… Interesting. 🙂