We are no longer accepting contributions to Documentation. Please see our post on meta.

Python Language

Functional Programming in Python All Versions

Python 2.x

2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7

Python 3.x

3.0
3.1
3.2
3.3
3.4
3.5
3.6
[3.7]

Functional programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input.below are functional techniques common to many languages: such as lambda, map, reduce.

This draft deletes the entire topic.

Examples

  • 1

    An anonymous, inlined function defined with lambda. The parameters of the lambda are defined to the left of the colon. The function body is defined to the right of the colon. The result of running the function body is (implicitly) returned.

    s=lambda x:x*x
    s(2)    =>4
    
  • 0

    Filter takes a function and a collection. It returns a collection of every item for which the function returned True.

    arr=[1,2,3,4,5,6]
    [i for i in filter(lambda x:x>4,arr)]    # outputs[5,6]
    
  • 0

    Map takes a function and a collection of items. It makes a new, empty collection, runs the function on each item in the original collection and inserts each return value into the new collection. It returns the new collection.

    This is a simple map that takes a list of names and returns a list of the lengths of those names:

    name_lengths = map(len, ["Mary", "Isla", "Sam"])
    print(name_lengths)    =>[4, 4, 3]
    
  • 0

    Reduce takes a function and a collection of items. It returns a value that is created by combining the items.

    This is a simple reduce. It returns the sum of all the items in the collection.

    total = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
    print(total)    =>10
    
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about Functional Programming in Python? Ask Question

Topic Outline


    We are no longer accepting contributions to Documentation. Drafts cannot be modified.