Advanced python functions – part two

Etiris Magazine
5 min readJan 12, 2023

--

Unleash the power of advanced Python functions: Learn how to use itertools, functools, operator and more to improve your coding abilities

Python is a powerful programming language that offers a wide range of built-in functions and modules to make coding easier and more efficient. In the first part of this series, we covered some of the most commonly used built-in functions such as map, reduce, filter, zip, and enumerate. These functions are essential for any Python developer and are widely used in data manipulation, data analysis and other software development tasks.

In this second installment of the series, we’re going to dive deeper into the Python standard library and explore some more advanced functions that can greatly enhance your coding abilities. These functions are not as well known as the ones covered in the first part, but they can be just as powerful and useful.

The itertools module offers a function called groupby() which allows you to group items in an iterable based on a key function. This function is very useful for data analysis and manipulation tasks. The functools module offers a function called partial() which allows you to create a new function with some of the arguments pre-filled. This function is very useful for creating reusable code, as well as for simplifying complex function calls. The operator module offers two functions called attrgetter() and itemgetter() which allow you to easily access an attribute or item of an object, respectively. These functions are very useful for sorting lists of objects based on their attributes or items.

In this article, we will be going through practical examples of how to use these functions and how they can be applied to solve real-world problems. These functions are not as popular as map, reduce, filter, zip, and enumerate but they are still very powerful and useful. By becoming familiar with these tools, you can greatly enhance your coding abilities and make your code more efficient, readable, and reusable.

itertools.groupby()

The groupby() function from the itertools module allows you to group items in an iterable based on a key function. This can be extremely useful for data analysis and manipulation tasks. The function takes two arguments: an iterable, and a function to determine the key of each element. The function returns an iterator that produces pairs (key, group) where each group is a sequence of elements that have the same key. Here’s an example of how you can use it to group a list of words by their first letter:

from itertools import groupby

words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

for first_letter, group in groupby(sorted(words), key=lambda x: x[0]):
print(first_letter, list(group))

This will output:

a ['apple']
b ['banana']
c ['cherry']
d ['date']
e ['elderberry']
f ['fig']

As you can see, the function groups the words by their first letter, it starts by sorting the list of words and then it applies the key function to each element to determine the key which is the first letter of the word, then it iterates over the result, and for each key, it returns the associated group of elements.

functools.partial()

The partial() function from the functools module allows you to create a new function with some of the arguments pre-filled. This can be very useful for creating reusable code, as well as for simplifying complex function calls. The function takes a function and any number of arguments and keyword arguments, and it returns a new callable object that when called, it applies the original function to the given arguments and keyword arguments, and any additional arguments and keyword arguments passed to the callable object. Here’s an example of how you can use it to create a new function that multiplies a number by 10:

from functools import partial

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

times_10 = partial(multiply, 10)

print(times_10(5)) # 50

In this example, we define a function multiply that takes two arguments and returns the product of them. Then we use the partial function to create a new function times_10 that is equivalent to the multiply function with the first argument fixed to 10. So when we call times_10(5) it is equivalent to calling multiply(10,5) which returns 50.

operator.attrgetter() and operator.itemgetter()

The attrgetter() and itemgetter() functions from the operator module allow you to easily access an attribute or item of an object, respectively. These can be very useful for sorting lists of objects based on their attributes or items. attrgetter() function returns a callable that when called, it returns the value of the given attribute of the input object. itemgetter() function returns a callable that when called, it returns the value of the given item of the input object. Here’s an example of how you can use attrgetter() to sort a list of objects by their name attribute:

import operator

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

people = [Person('Bob', 30), Person('Charlie', 25), Person('Alice', 35)]

sorted_people = sorted(people, key=operator.attrgetter('name'))

for person in sorted_people:
print(person.name)

This will output:

Alice
Bob
Charlie

Here we defined a Person class with two attributes name and age, then we created a list of three person objects. Then we use the sorted function to sort the list of people by the name attribute. We use the attrgetter function to get the name attribute of each person object and use it as the key for sorting.

And here’s an example of how you can use itemgetter() to sort a list of tuple by the second item:

data = [(1, 'a'), (3, 'b'), (2, 'c')]

sorted_data = sorted(data, key=operator.itemgetter(1))

for item in sorted_data:
print(item)

This will output:

(1, 'a')
(3, 'b')
(2, 'c')

In this example, we use the itemgetter() function to get the second item of each tuple and use it as the key for sorting.

In conclusion, the Python standard library offers a wide range of advanced functions that can greatly enhance your coding abilities. The functions we covered in this article, such as itertools.groupby(), functools.partial(), operator.attrgetter(), and operator.itemgetter(), are not as well-known as the functions covered in the first part of this series, but they can be just as powerful and useful. Understanding and utilizing these functions can lead to more efficient, readable, and reusable code.

It’s important to note that this is not an exhaustive list of advanced python functions, and there are many more powerful functions available in the Python standard library. As a Python developer, it’s essential to continue learning and exploring these functions to improve your skills and abilities. This way you can write better and more efficient code, and solve more complex problems.

In addition, don’t forget to take into account that good code is not only about using advanced functions but also about writing clean, readable and well-documented code, and following good coding practices.

--

--