Sobes.tech
Junior — Middle

Can you list and describe the main concepts of functional programming implemented in Python?

sobes.tech AI

Answer from AI

Python implements the main concepts of functional programming:

  • Functions as first-class objects — functions can be passed as arguments, returned from other functions, and assigned to variables.

  • Pure functions — functions without side effects that depend only on input parameters.

  • Higher-order functions — functions that accept other functions as arguments or return them. For example, map(), filter(), reduce().

  • Lambda functions — anonymous functions that are convenient for short operations.

  • Immutability — although Python is not strictly immutable, it is recommended to use immutable data structures for a functional style.

  • Recursion — using functions that call themselves instead of loops.

Example of using map and filter:

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
even = list(filter(lambda x: x % 2 == 0, numbers))
print(squared)  # [1, 4, 9, 16, 25]
print(even)     # [2, 4]

Thus, Python supports a functional programming style, allowing for more declarative and concise code.