3.4. Operator¶
operator is a built-in Python library that exports a set of efficient functions corresponding to the intrinsic operators of Python. This section will show you some useful methods of this module.
3.4.1. operator.itemgetter: Get Multiple Items From a List or Dictionary¶
Normally, to access multiple indices from a list, you need to use list comprehension:
fruits = ['apple', 'orange', 'banana', 'grape']
[fruit for fruit in fruits if fruits.index(fruit) in [1, 3]]
['orange', 'grape']
To do the same thing with simpler syntax, use operator.itemgetter
instead:
from operator import itemgetter
itemgetter(1, 3)(fruits)
('orange', 'grape')