Advanced Python Functions

Etiris Magazine
4 min readJan 7, 2023

--

Streamline Your Code with map(), reduce(), filter(), zip(), and enumerate()

Python is a versatile and widely-used programming language, offering a range of built-in functions and libraries to help you accomplish various tasks. In this article, we will delve into some advanced functions that can streamline your code and make it more efficient. From the map() function, which applies a specified function to each element of an iterable and returns a new iterable with the modified elements, to the enumerate() function which adds a counter to an iterable and returns an iterable of tuples, these functions can help you write cleaner and more concise code. Let’s take a closer look at these advanced Python functions and see how to use them in your code.

map()

The map() function applies a specified function to each element of an iterable (such as a list, tuple, or string) and returns a new iterable with the modified elements.

For example, you can use map() to apply the len() function to a list of strings and get a list of the lengths of each string:

def get_lengths(words):
return map(len, words)

words = ['cat', 'window', 'defenestrate']
lengths = get_lengths(words)
print(lengths) # [3, 6, 12]

You can also use map() with multiple iterables by providing multiple function arguments. In this case, the function should accept as many arguments as there are iterables. The map() function will then apply the function to the elements of the iterables in parallel, with the first element of each iterable being passed as arguments to the function, the second element of each iterable being passed as arguments to the function, and so on.

For example, you can use map() to apply a function to two lists element-wise:

def multiply(x, y):
return x * y

a = [1, 2, 3]
b = [10, 20, 30]
result = map(multiply, a, b)
print(result) # [10, 40, 90]

reduce()

The reduce() function is a part of the functools module in Python and allows you to apply a function to a sequence of elements in order to reduce them to a single value.

For example, you can use reduce() to multiply all the elements of a list:

from functools import reduce

def multiply(x, y):
return x * y

a = [1, 2, 3, 4]
result = reduce(multiply, a)
print(result) # 24

You can also specify an initial value as the third argument to reduce(). In this case, the initial value will be used as the first argument to the function and the first element of the iterable will be used as the second argument.

For example, you can use reduce() to calculate the sum of a list of numbers:

from functools import reduce

def add(x, y):
return x + y

a = [1, 2, 3, 4]
result = reduce(add, a, 0)
print(result) # 10

filter()

The filter() function filters an iterable by removing elements that do not satisfy a specified condition. It returns a new iterable with only the elements that satisfy the condition.

For example, you can use filter() to remove all the even numbers from a list:

def is_odd(x):
return x % 2 == 1

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(is_odd, a)
print(odd_numbers) # [1, 3, 5, 7, 9]

You can also use filter() with a lambda function as the first argument:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(lambda x: x % 2 == 1, a)
print(odd_numbers) # [1, 3, 5, 7, 9]

zip()

The zip() function combines multiple iterables into a single iterable of tuples. The zip() function stops when the shortest iterable is exhausted.

For example, you can use zip() to combine two lists into a list of tuples:

a = [1, 2, 3]
b = ['a', 'b', 'c']
zipped = zip(a, b)
print(zipped) # [(1, 'a'), (2, 'b'), (3, 'c')]

You can also use zip() with more than two iterables:

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [True, False, True]
zipped = zip(a, b, c)
print(zipped) # [(1, 'a', True), (2, 'b', False), (3, 'c', True)]

You can unpack the tuples in a zip() object by using the * operator in a function call or a list comprehension:

def print_tuples(a, b, c):
print(f'a: {a}, b: {b}, c: {c}')

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [True, False, True]
zipped = zip(a, b, c)

# Unpack the tuples in a function call
for t in zipped:
print_tuples(*t)

# Unpack the tuples in a list comprehension
unzipped = [print_tuples(*t) for t in zipped]

enumerate()

The enumerate() function adds a counter to an iterable and returns an iterable of tuples, where each tuple consists of the counter and the original element.

For example, you can use enumerate() to loop over a list and print the index and value of each element:

a = ['a', 'b', 'c']
for i, element in enumerate(a):
print(f'{i}: {element}')

# Output:
# 0: a
# 1: b
# 2: c

You can also specify a start value for the counter as the second argument to enumerate():

a = ['a', 'b', 'c']
for i, element in enumerate(a, 1):
print(f'{i}: {element}')

# Output:
# 1: a
# 2: b
# 3: c

Conclusion

In this article, we covered some advanced Python functions that can be useful in your code. We looked at the map(), reduce(), filter(), zip(), and enumerate() functions, and provided examples of how to use them. These functions can help you write more efficient and concise code, and are worth exploring further.

If you liked the article check out part two of advanced python functions.

--

--