Built-In Transform Functions in Python

Day 27 in #100DaysOfCode

Python has grown in popularity among data scientists and other developers who must work with big volumes of data, and this is not by chance. The Python standard library includes routines for manipulating data sequences. And you should employ these if you find yourself in need of such a procedure.

The filter() method

The filter() method filters the provided sequence using a function that examines each element in the sequence to see if it is true or false.


def fun(variable):
    letters = ['a', 'e', 'i', 'o', 'u']
    if (variable in letters):
        return True
    else:
        return False
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

# using filter function
filtered = filter(fun, sequence)

print('The filtered letters are:')
for s in filtered:
    print(s)

Output:

The filtered letters are:
e
e

The map() function

The map() method provides a map object (an iterator) with the results of applying the provided function to each item of an iterable (list, tuple etc.)

def addition(n):
    return n + 3

# We double all numbers using map()
numbers = (2, 3, 4, 5)
result = map(addition, numbers)
print(list(result))

Output:

[5, 6, 7, 8]

Process finished with exit code 0