🎓 A1Learner
🔍

Python The operator Module

The operator module holds ready-made picker functions. itemgetter picks items by position or by key.

Sort by one field

itemgetter(1) picks the second item. sorted uses it as the key.

from operator import itemgetter
rows = [("bo", 30), ("ana", 25), ("cy", 35)]
print(sorted(rows, key=itemgetter(1)))

Read an attribute as a key

attrgetter reads the age attribute. The youngest person comes out of min.

from operator import attrgetter
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
people = [Person("bo", 30), Person("ana", 25)]
youngest = min(people, key=attrgetter("age"))
print(youngest.name)

Call a method by name

methodcaller builds a small caller. It calls upper on the text you pass in.

from operator import methodcaller
shout = methodcaller("upper")
print(shout("hello"))

Keep operators in a table

The dict maps a word to a function. The code picks a function, then calls it.

import operator
table = {"add": operator.add, "mul": operator.mul}
print(table["add"](3, 4))
print(table["mul"](3, 4))

Example

from operator import itemgetter

records = [
    ("cy", "sales", 3),
    ("ana", "tech", 5),
    ("bo", "sales", 2),
    ("dee", "tech", 1),
]
for row in sorted(records, key=itemgetter(1, 0)):
    print(row)

Key points

  • Use itemgetter to pick items by position or by key.
  • Use attrgetter to pick values by attribute name.
  • Use methodcaller to build a caller for a named method.
  • The module also holds plain operator functions, like operator.add.
  • You can store those functions in a dict or a list.
  • Code can then pick one by name.
  • The operator module holds picker functions that are ready to use.

In this example, each record holds a name, a team, and a count. One itemgetter picks field 1, then field 0. So sorted orders by team first. Records on the same team then order by name. No lambda is needed for this key. The loop prints each sorted record on its own line.

Note

itemgetter(1, 0) reads field 1 first.

Ties in a sort then fall back to field 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How do you sort tuples by their second field, with no lambda?