the sorted call then sorts the results by their first elementwhich is distance this is complicated piece of code and isn' object-oriented at all you may want to break it down into normal for loop to ensure you understand what the generator expression is doing it might also be good exercise to imagine how this code would look if you were to pass key argument into the sorted function instead of constructing tuple the yield statement is bit less complicatedit pulls the second value from each of the first (distancecolor_datatuples in more concrete termsit yields the ((rgb)color_nametuple for the values with the lowest distance orif you prefer more abstract termsit yields the target' -nearest neighbors in the given model the remaining code is just boilerplate to test this methodit constructs the model and color generatorprimes the coroutineand prints the results in for loop the two remaining tasks are to choose color based on the nearest neighborsand to output the results to csv file let' make two more coroutines to take care of these tasks let' do the output first because it can be tested independentlydef write_results(filename="output csv")with open(filename" "as filewriter csv writer(filewhile truecolorname yield writer writerow(list(color[name]results write_results(next(resultsfor in range( )print(iresults send(((iii) )this coroutine maintains an open file as state and writes lines of code to it as they are sent in using send(the test code ensures the coroutine is working correctlyso now we can connect the two coroutines with third one the second coroutine uses bit of an odd trickfrom collections import counter def name_colors(get_neighbors)color yield while truenear get_neighbors send(colorname_guess countern[ for in nearmost_common( )[ ][ color yield name_guess