For Python 2.x:
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times, filter
, map
, and reduce
can easily and efficiently serve typical purposes that most people attempt without these. Here's an example of their usage (I use lambda expressions in them - you can read up on lambda expressions here):
# filter
# in the interactive shell, use help(filter) for more info.
# filter takes a function and a list, and returns a list of
# the items that returned True for the given function.
# This example takes a list and returns one with the
# unallowed words removed.
words = ['This', 'sentence', 'has', 'unallowed', 'words']
unallowed = ['has', 'words']
remainder = filter(lambda x: x not in unallowed, words)
"""result ->
['This', 'sentence', 'unallowed']
"""
# map
# in the interactive shell, use help(map) for more info.
# map takes a function and a list, and returns a list of
# the items after applying the specified function to them.
# This example takes a list and returns one in which
# every index was squared.
data = [2, 5, 9, 16, 31, 35]
squared = map(lambda x: x*x, data)
"""result ->
[4, 25, 81, 256, 961, 1225]
"""
# reduce
# in the interactive shell, use help(reduce) for more info.
# reduce takes a function and a list, and returns a single
# value formed by taking the result of the function on the
# first two indices, then applying the function on that result
# and the third index, and so forth.
# This example takes a list and returns an integer calculated
# by multiplying all the indices together.
data = [1, 3, 4, 7, 8, 9]
reduce(lambda x, y: x * y, data)
"""result ->
6048
"""
With reduce, note that it is redundant to use this to sum all the indices in a list, as there is a built-in function for that, sum
. (This is because getting the sum of a list is such a common need.)