's' parameter explain?

Say we have a list of strings we want to sort by the last letter of the string.

strs = [‘xc’, ‘zb’, ‘yd’ ,‘wa’]

Write a little function that takes a string, and returns its last letter.

This will be the key function (takes in 1 value, returns 1 value).

def MyFn(s):
return s[-1]

Now pass key=MyFn to sorted() to sort by the last letter:

print(sorted(strs, key=MyFn)) ## [‘wa’, ‘zb’, ‘xc’, ‘yd’]

In the code you provided, the ‘key’ parameter in the sorted() function is used to specify a custom sorting criteria. The key parameter takes a function that will be called on each element of the iterable (in this case, the list of strings strs), and the sorting is based on the values returned by this function.

Here’s a breakdown of the code:

strs = ['xc', 'zb', 'yd', 'wa']

# Define a function MyFn that takes a string and returns its last letter
def MyFn(s):
    return s[-1]

# Use sorted() with the key parameter set to MyFn
# This sorts the list of strings based on the last letter of each string
sorted_result = sorted(strs, key=MyFn)

# Print the sorted result
print(sorted_result)  # Output: ['wa', 'zb', 'xc', 'yd']

In this case, MyFn is a function that takes a string s and returns its last letter using Python’s indexing (s[-1]). When sorted() is called with key=MyFn, it applies the MyFn function to each element in the list strs and uses the resulting values as the basis for sorting. As a result, the list is sorted based on the last letter of each string, and the final output is ['wa', 'zb', 'xc', 'yd'].

1 Like