Skip to content

Instantly share code, notes, and snippets.

@gengwg
Created May 10, 2025 00:55
Show Gist options
  • Save gengwg/7ef7ecda76f9ebc3f5c3c2fdf1ab4981 to your computer and use it in GitHub Desktop.
Save gengwg/7ef7ecda76f9ebc3f5c3c2fdf1ab4981 to your computer and use it in GitHub Desktop.
python itemgetter with examples.

The itemgetter function from Python's operator module creates a callable that retrieves items from objects using indices (for sequences like lists/tuples) or keys (for mappings like dictionaries). It is efficient and commonly used with functions like sorted(), max(), and min() for clean, readable code.

Importing itemgetter

from operator import itemgetter

Examples

  1. Basic Usage with a List

    data = ['a', 'b', 'c', 'd']
    
    get_second = itemgetter(1)
    print(get_second(data))  # Output: 'b'
    
    get_multiple = itemgetter(1, 3)
    print(get_multiple(data))  # Output: ('b', 'd')
  2. Using with Dictionaries

    person = {'name': 'Alice', 'age': 30, 'job': 'Engineer'}
    
    get_age = itemgetter('age')
    print(get_age(person))  # Output: 30
  3. Sorting a List of Tuples

    students = [('Alice', 85, 20), ('Bob', 75, 22), ('Charlie', 90, 21)]
    
    # Sort by grade (index 1)
    sorted_by_grade = sorted(students, key=itemgetter(1))
    print(sorted_by_grade)  # Output: [('Bob', 75, 22), ('Alice', 85, 20), ('Charlie', 90, 21)]
  4. Sorting a List of Dictionaries by Multiple Keys

    people = [
        {'name': 'Alice', 'age': 30},
        {'name': 'Bob', 'age': 25},
        {'name': 'Charlie', 'age': 30}
    ]
    
    # Sort by 'age', then 'name'
    sorted_people = sorted(people, key=itemgetter('age', 'name'))
    print(sorted_people)
    # Output: [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 30}]
  5. Finding Maximum Using itemgetter

    max_student = max(students, key=itemgetter(1))
    print(max_student)  # Output: ('Charlie', 90, 21)

Comparison with lambda

  • itemgetter(1) is equivalent to lambda x: x[1].
  • Advantages of itemgetter:
    • Readability: Clearly expresses intent.
    • Performance: Faster for large datasets due to C-level optimization.

Key Takeaways

  • Use itemgetter to cleanly extract items by index/key.
  • Ideal for sorting, finding max/min, or extracting data from nested structures.
  • Supports multiple indices/keys to return tuples for multi-level comparisons.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment