3

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.

The solution to the problem is:

def last(a): 
   return a[-1]
def sort_last(tuples):  
   return sorted(tuples, key=last)

Can anyone help me to understand what arguments are passed to the last function? Specifically, what does a contain?

We have not passed any values or arguments while calling the last function in the sorted method.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
rsn
  • 39
  • 1
  • 2
  • *You* didn't call `last()` at all. `sorted()` is the one calling that function, and does so once for each element of the sequence passed to it. – jasonharper Jul 02 '21 at 16:56
  • Does this answer your question? [How does the key argument in python's sorted function work?](https://stackoverflow.com/questions/32238196/how-does-the-key-argument-in-pythons-sorted-function-work) – Gino Mempin Jul 03 '21 at 04:41

2 Answers2

1

This is what is called a "lambda".

It's passing the current element of your list to the function "last" which will then get the last element of the tuple.

So the parameter "a" is the tuple being currently processed.

Tim Woocker
  • 1,883
  • 1
  • 16
  • 29
  • 2
    This is not a lambda. Lambdas say `lambda` at the front. We're passing a named function as the `key` here. – user2357112 Jan 12 '16 at 20:09
  • It's using a value from a list being processed by the sorted function. https://en.wikipedia.org/wiki/Lambda_calculus It's a variation of a lambda. – Tim Woocker Jan 12 '16 at 20:12
  • 1
    Not relevant. Lambdas are a specific syntactical construct for creating functions; whether a function is a lambda or not has nothing to do with how the function is used. – user2357112 Jan 12 '16 at 20:14
  • @crey4fun Thank you for your help. – rsn Jan 12 '16 at 20:51
-1

Iterating through a tuple via for loop - (Sorted initial list with 2nd element of the tuple.) Nested for loops - comparing original tuple with the sorted 2nd element list.

tuple1 = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

List2 =[]
List3 =[]

for t in tuple1:
    List2.append(t[1],)

List2.sort()
print(List2)

for l in List2:
    for q in tuple1:
        if l == int(q[1],):
            List3.append(q)

print(List3)
  • 2
    Hi user13557829, please read up on [writing a good answer](https://stackoverflow.com/help/how-to-answer). Enjoy your stay here at SO :) – Diggy. May 16 '20 at 23:08