Comparison of how to use higher-order functions in Python 2 and 3

Every time I use Python, I check how to use higher-order functions (map, filter, reduce), so I'll leave it as a memo.

Also, I recently started studying Python 3, but since the writing style is slightly different between Python 2 and 3, I will write both for comparison.

What is a higher-order function in the first place is a function that takes a function as an argument. For example, it is used when you want to perform some processing on each element of the array.

Execution environment

map function

It is used when you want to process all elements </ font> of the array. In the following example, all the elements of the array are doubled and output.

  • Python 2
print map(lambda x: x * 2, range(1, 5))
  • Python 3
print (list(map(lambda x: x * 2, range(1, 5))))
  • Execution result
[2, 4, 6, 8]

filter function

It is used when you want to process only the elements that match the condition </ font> in the array. In the following example, only even numbers are extracted from the elements of the array.

  • Python 2
print filter(lambda x: x % 2 == 0, range(1, 5))
  • Python 3
print (list(filter(lambda x: x % 2 == 0, range(1, 5))))
  • Execution result
[2, 4]

reduce function

Use this when you want to combine multiple elements into one </ font>. Specifically, two elements are extracted from the beginning of the array and processed, and then the result and the next element are processed, and so on.

However, in Python 3, the reduce function has been removed from the core Python functions and can only be used by importing the functools </ font> module.

In the following example, the sum of all the elements of the array is calculated.

  • Python 2
print reduce(lambda x, y: x + y, range(1, 5))
  • Python 3
import functools

print (functools.reduce(lambda x, y: x + y, range(1, 5)))
  • Execution result
10

It's partly because I'm new to Python 3, but my personal impression is that Python 2 is simpler to write ...

Reference material

  • http://www.python-course.eu/python3_lambda.php

Recommended Posts