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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Rwiddhi Chakraborty](https://secure.gravatar.com/avatar/aedb2006cdd8a6310a327146c57bb36f?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Rwiddhi Chakraborty
2,447 Pointsitemgetter
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.
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](https://uploads.teamtreehouse.com/production/profile-photos/1153532/micro_image.jpg)
Chris Freeman
Treehouse Moderator 68,425 PointsThe 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'>
SPOILER ALERT
sorted_fruit = sorted(fruit_list, key=itemgetter(1))
<!-- *JavaScript provided by Steven Parker --> </div>
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