Query on list : python google class list exercise

69 views
Skip to first unread message

Rao

unread,
Sep 25, 2017, 6:18:52 AM9/25/17
to Python GCU Forum
Hello All,

Am a new to python.
I browsed through the google python sessions in youtube and working on the respective session exercises too.

The exercise is:

# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.

I could do it as below, but have few queries on this.

def func(tup):
  print "Value is ",tup
  return tup[-1]
 
def sort_last(tuples):
  for tup in tuples:
   return sorted(tuples, key=func)


Query 1 : 
We are passing key as func to "sorted", but did not pass any parameters to the function.
How does this parameter passing happens automatically in this context.

Query 2: 
The last line of the code is -> return sorted(tuples, key=func). 
It should return after the first iteration of the for loop. But it passes through the all the iterations of for loop.

Query 3:
func is returning last element of the respective tupple to the sort_last.
It is a value. How does it help the sorted function to tuple based on the last element.
How does it derive that it has to sort based on the last element.

Thanks in advance.
Rao

Reply all
Reply to author
Forward
0 new messages