Member-only story
Understanding itemgetter vs attrgetter in python
When working with data in Python, whether stored in lists, tuples, dictionaries, or custom objects, you’ll often need to access specific elements or attributes. The operator
module offers two powerful utility functions—itemgetter
and attrgetter
that simplify this process while keeping your code clean and readable.
In this blog post, we’ll dive into what itemgetter
and attrgetter
are, when to use them, and how they can make your Python code more efficient.
Read for free: https://allwin-raju.medium.com/understanding-itemgetter-vs-attrgetter-in-python-38a04405fe80?sk=c2cc2faccd607ab452392dba9ecc81a8
What is itemgetter?
itemgetter is a function from the operator module designed to retrieve items from sequences (like lists or tuples) or mappings (like dictionaries) using an index or a key. It’s handy when sorting or filtering data.
Syntax
from operator import itemgetter
itemgetter(index_or_key, ...)
Sorting a List of Tuples:
from operator import itemgetter
data = [('Alice', 25), ('Bob', 30), ('Charlie', 20)]
# Sort by the second item (age)
sorted_data = sorted(data, key=itemgetter(1))
print(sorted_data) # Output: [('Charlie', 20), ('Alice', 25), ('Bob'…