The operator Module

The operator module turns Python's operators and lookups into plain, reusable functions, so you can pass things like "add", "get item 1", or "call .upper()" anywhere a function is expected.

Learn The operator Module in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

It's the secret behind clean sort keys and fast reductions: itemgetter , attrgetter , and methodcaller replace fiddly lambdas with faster, more readable building blocks.

itemgetter(i) returns a function that does obj[i] . That's exactly the shape sorted() wants for its key , so sorting a list of tuples or dict items becomes a one-liner that reads like English:

When you work with objects instead of tuples, use attrgetter('field') to read an attribute. And methodcaller('name', args...) builds a function that calls a method on each item — ideal inside map() :

Think of it as matching the access style: itemgetter for [ ] , attrgetter for .attr , and methodcaller for .method() .

Every operator has a function form: operator.add , operator.mul , operator.gt , operator.contains , and so on. These shine when a function needs a binary operation as an argument — most famously functools.reduce :

Replace each ___ with the right helper from operator so the leaderboard sorts by score (highest first).

❌ Calling itemgetter on the whole list instead of passing it as a key

✅ Pass the index; sorted applies the getter to each item

❌ Using attrgetter on a dict (dicts use keys, not attributes)

❌ Forgetting methodcaller returns a callable, not a result

Sort a list of sales records by region then revenue (highest first within a region), and compute the grand total with reduce and operator.add .

Lesson complete — your sort keys are pristine!

You can reach for itemgetter to sort tuples and dict items, attrgetter to sort objects, methodcaller to call a method on every element, and operator functions like add and mul to power reduce — all faster and clearer than lambdas.

🚀 Up next: binary data with struct — pack and unpack raw bytes into Python values.

Practice quiz

What does itemgetter(1) return when used as a callable?

  • The value 1
  • A list of all second elements

itemgetter(1) builds a function that does obj[1], ideal as a sort key.

What is sorted(people, key=itemgetter(1)) for people = [('Ada',36),('Ben',28),('Cleo',41)]?

  • Ben
  • Ada
  • Cleo

Answer: Ben. It sorts by element 1 (age) ascending: 28, 36, 41.

How do you sort by element 1, then break ties using element 0?

  • itemgetter(1)(0)

Passing several indexes, itemgetter(1, 0), returns a tuple key sorting by 1 then 0.

Which helper reads an attribute, e.g. to sort objects by their .age?

  • itemgetter('age')
  • attrgetter('age')
  • methodcaller('age')
  • getattr_sorted('age')

Answer: attrgetter('age'). attrgetter('age') builds a function that does obj.age, matching attribute access.

What does methodcaller('strip') do when mapped over strings?

  • Calls .strip() on each string, returning the stripped results
  • Returns the strip method object only
  • Sorts the strings
  • Raises an error because strip needs arguments

Answer: Calls .strip() on each string, returning the stripped results. methodcaller('strip') builds a function that calls .strip() on each element it receives.

What is reduce(operator.mul, [1, 2, 3, 4, 5])?

  • 15
  • 25
  • 120
  • 5

Answer: 120. It folds multiplication across the list: 1*2*3*4*5 = 120.

Which call matches the three access styles correctly?

itemgetter does obj[k], attrgetter does obj.attr, and methodcaller does obj.m(args).

Why does attrgetter('age') fail on a plain dict like {'age': 30}?

  • Dicts are immutable
  • attrgetter requires two arguments
  • It actually works fine
  • Dicts use keys (indexing), not attributes, so itemgetter('age') is needed

Answer: Dicts use keys (indexing), not attributes, so itemgetter('age') is needed. A dict has no .age attribute; use itemgetter('age') which does dict['age'].

What does operator.contains([1, 2, 3], 2) return?

  • False
  • True
  • 2

Answer: True. operator.contains is the function form of 'in', and 2 is in the list, so it returns True.

When is passing operator.add more useful than writing + directly?

  • Never; + is always required
  • Only for string concatenation
  • When a function needs a binary operation as an argument, e.g. reduce(operator.add, nums)
  • When adding exactly two literals

Answer: When a function needs a binary operation as an argument, e.g. reduce(operator.add, nums). You can't pass + as an argument, but operator.add is a callable you can hand to reduce, map, etc.