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

James N
James N
17,864 Points

I am completely stumped (and it's saying task 1 isn't passing)

I don't get this codechallenge. i am on task 2, and i (yes, i'm dumb) don't at all get what itemgetter does and how to use it. i know i have to sort by the 2nd item in each tuple (the number) but i don't know how to tell itemgetter to go and get it!

i used a slice for the first, (to select all the tuples), and within the tuples, used the 2nd brackets to select the number in the tuple.

But, even so, i don't get it!

Thanks in advance, James.

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:][2]))

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Just pass 1, the index of the second item in each tuple, to itemgetter:

from operator import itemgetter

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

sorted_fruit = sorted(fruit_list, key=itemgetter(1))
James N
James N
17,864 Points

Thing is, i couldn't think of what to pass into itemgetter. i don't 100% get how that would work. i'll still try it, but could you (or someone else on the world of the net) explain the logic of this?

James N
James N
17,864 Points

UPDATE: Thanks for your help! just tried it now, and it works!

However, i would still like someone to explain the logic of this, thanks.