itemgetter() in Python (original) (raw)

Last Updated : 23 Jul, 2025

The itemgetter() function from the operator module in Python is used to extract specific items from a list, tuple, or dictionary. It allows easy retrieval of elements without writing lambda functions.

**Example:

Python `

from operator import itemgetter

a = [10, 20, 30, 40] val = itemgetter(2) print(val(a))

`

Explanation:

Syntax

from operator import itemgetteritemgetter(index1, index2, ...)

Parameters

Return Value

Examples of itemgetter() method

Python `

from operator import itemgetter

a = [10, 20, 30, 40] val = itemgetter(1, 3) print(val(a))

`

**Explanation: This code uses itemgetter() from the operator module to create a callable that retrieves elements at the specified indices (1 and 3) from the list lst. The get_items(lst) call fetches the elements at indices 1 and 3 (which are 20 and 40), and the result (20, 40) is printed.

2. Using itemgetter() for Sorting

Python `

from operator import itemgetter

a = [("Rahul", 85), ("Raj", 90), ("Jay", 80)] b = sorted(s, key=itemgetter(1)) print(b)

`

Output

[('Jay', 80), ('Rahul', 85), ('Raj', 90)]

**Explanation: This code sorts a list of tuples, students, based on the second element (the score) using itemgetter(1) from the operator module. The sorted() function sorts the tuples in ascending order by the scores, and the result is stored in sorted_students and printed.

Python `

from operator import itemgetter

d = {"a": 10, "b": 20, "c": 30} get_value = itemgetter("b") print(get_value(d))

`

**Explanation: This code uses itemgetter() from the operator module to create a callable that retrieves the value associated with the key "b" from the dictionary d. The get_value(d) call fetches the value corresponding to the key "b" (which is 20), and the result 20 is printed.