Python - NameError: name itemgetter not defined

Ricky Nelson picture Ricky Nelson · Apr 18, 2016 · Viewed 16.9k times · Source

I just started learning Python came across this very simple code could not get it right:

import operator;

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=itemgetter(1))

I got the error:

NameError: name 'itemgetter' is not defined.

Any idea?

Answer

Suresh2692 picture Suresh2692 · Apr 18, 2016

you must import the module like,

import operator

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=operator.itemgetter(1))