Open In App

itemgetter() in Python

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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))

Output
30

Explanation:

  • itemgetter(2) creates a callable object that retrieves the item at index 2.
  • The list a contains:
    • Index 0 → 10
    • Index 1 → 20
    • Index 2 → 30
  • val(lst) returns the value at index 2 → 30.

Syntax

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

Parameters

  • index1, index2, ...: The positions of elements to extract.

Return Value

  • Returns the value(s) at the specified index or key.
  • When multiple indices are used, it returns a tuple containing the values.

Examples of itemgetter() method

1. Extracting Multiple Elements

Python
from operator import itemgetter

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

Output
(20, 40)

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.

3. Extracting Values from Dictionaries

Python
from operator import itemgetter

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

Output
20

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads