Quick actions

cmd+k|ctrl+k

Navigation

Languages

Iterable Functions - 1

Snippet info

Language

Python

Visibility

public

Author

apizzimenti

Created

2016-03-20T20:36:34Z

Updated

2016-03-20T20:38:06Z

'''
This is a brief first part of a series on Python's built-ins that operate on 
iterables. They are very useful in functional programming, as they avoid
mutable and state data.
'''

# filter(function, iterable) takes a function and an iterable. The function
# is called on each item in the iterable, and a new iterable (of the same type
# as the original iterable) is created and returned as a filter object.

a = [1, 2, 3, 4]

def by_two(arg):
    return arg * 2
    
b = list(filter(by_two, a))
print(b)


# map(function, iterable, ...) takes a function an an iterable. Like filter,
# map applies the function to each variable in the iterable, but it returns a
# map object with the results as a list.

def by_three(arg):
    return arg * 3
    
c = list(map(by_three, a))
print(c)


# reduce(function, iterable [, initializer]) takes a functoin and an iterable
# (again). This time, the function is applied to each value in the iterable
# to reduce the iterable to a single value. If the initializer is present, it
# serves as a fallback and is returned when the iterable is empty.

import functools as f

def get_sum(accum, new):
    return accum + new
    
d = f.reduce(get_sum, a)
e = f.reduce(get_sum, a, 10)
print(d)
print(e)
INFO