Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndy McDonald
Python Development Techdegree Graduate 13,801 PointsDont 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
Treehouse Moderator 28,720 PointsI 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)]