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 trial

Python Functional Python Functional Workhorses Sorting

itemgetter

Whenever I'm trying to run this code, I get an error: "Tuple index out of range". What does it mean? How do I fix it?

Also, during my test runs, when I'm replacing the values of the second item in each tuple to 1 or 2, the program runs perfectly. Can anyone explain this? Thanks.

sorting.py
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[0][1]))

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

The argument to itemgetter (docs) is relative to the items being sorted. Since tuples are sorted, you provide the index to the item within the tuple: (1)

I'll bet you can get it now. But if you're still stuck... <button' onclick='$("#spoiler").slideDown("slow");$(this).remove()'>Press to Reveal Spoiler</button> <div id='spoiler' style='display:none'>


:warning: SPOILER ALERT


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

<!-- *JavaScript provided by Steven Parker --> </div>

Luis Manuel Lopez Hidalgo
seal-mask
.a{fill-rule:evenodd;}techdegree
Luis Manuel Lopez Hidalgo
Full Stack JavaScript Techdegree Student 23,195 Points
          sorted_fruit = sorted(fruit_list, key=itemgetter(1))

sorted() check the key you provide on each item of the fruit_list. The key you are providing is not posible to find because it's always searching for the *the second element of the first tuple fruit_list[0][1] *. In the code above the key you are providing is the second element of each iterable item in the fruit_list. Hope this help