Skip to content

Python itemgetter() function

  • by

The itemgetter() function is a utility function provided by the operator module in Python. It is used to retrieve items from an iterable based on their indices or keys.

The itemgetter() function takes one or more arguments, which can be indices or keys, and returns a callable object. This callable object can be used to extract the corresponding elements from the iterable.

The syntax for the itemgetter() function is as follows:

itemgetter(*items)

The itemgetter() function takes one or more arguments, *items, which can be indices or keys. It returns a callable object that can be used to extract the corresponding items from an iterable.

Python itemgetter() function example

Here’s an example that demonstrates the usage of the itemgetter() function in Python:

from operator import itemgetter

# Example list of dictionaries
students = [
    {'name': 'Alice', 'age': 22, 'grade': 'A'},
    {'name': 'Bob', 'age': 19, 'grade': 'B'},
    {'name': 'Charlie', 'age': 20, 'grade': 'A'},
    {'name': 'David', 'age': 21, 'grade': 'C'},
]

# Create an itemgetter object to retrieve the 'name' and 'age' keys from each dictionary
get_name_and_age = itemgetter('name', 'age')

# Retrieve 'name' and 'age' using itemgetter
name_and_age = [get_name_and_age(student) for student in students]
print(name_and_age)

Output:

Python itemgetter() function

Another example

from operator import itemgetter

# Example list of tuples
students = [
    ("Alice", 22, "A"),
    ("Bob", 19, "B"),
    ("Charlie", 20, "A"),
    ("David", 21, "C"),
]

# Create an itemgetter object to retrieve the second element (age) from each tuple
get_age = itemgetter(1)

# Retrieve ages using itemgetter
ages = [get_age(student) for student in students]
print(ages)
# Output: [22, 19, 20, 21]

Note: itemgetter() can also accept multiple arguments, allowing you to extract multiple elements at once. For example, itemgetter(0, 2) would return a callable object that retrieves the first and third elements from each tuple.

Do comment if you have any doubts o suggestions on this Python method topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *