Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python Functional Workhorses Sorting

Andy McDonald
Andy McDonald
Python Development Techdegree Student 6,643 Points

Dont know how to use itemgetter

The video does a great job of explaining how to use item getter on objects with attributes but it has me wondering how to use itemgetter on a tuple....

from operator import itemgetter

fruit_list = [
    ('apple', 2),
    ('banana', 5),
    ('coconut', 1),
    ('durian', 3),
    ('elderberries', 4)

sorted_fruit = sorted(fruit_list, key=itemgetter(fruit_list[1])

1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 27,586 Points

I agree that itemgetter() is a little odd in its usage. But you're on the right track.

Since itemgetter creates an operator, it won't use fruit_list at all. It simply refers to a 'key' in the list.

You will notice the first element of the tuple is a letter. We use itemgetter(0) to sort by that key. And the second element is an index. We use itemgetter(1) to sort by that key. See below.

I think you can figure the rest out. Good luck with your Python journey!

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> fruit_list = [
...     ('apple', 2),
...     ('banana', 5),
...     ('coconut', 1),
...     ('durian', 3),
...     ('elderberries', 4)
... ]
>>> fruit_list
[('apple', 2), ('banana', 5), ('coconut', 1), ('durian', 3), ('elderberries', 4)]
>>> # try a sort by the FIRST element of the tuple
>>> sorted_alphabetically = sorted(fruit_list, key=itemgetter(0)) 
>>> sorted_alphabetically
[('apple', 2), ('banana', 5), ('coconut', 1), ('durian', 3), ('elderberries', 4)]
>>> # try a sort by the SECOND element of the tuple
>>> sorted_index = sorted(fruit_list, key=itemgetter(1) )
>>> sorted_index
[('coconut', 1), ('apple', 2), ('durian', 3), ('elderberries', 4), ('banana', 5)]