-1

I found a Practice question from Anand Chitipothu. I found an answer on gist for a question(Not cheating, just couldn't understand where to start because new to python). Since the guy who posted it doesn't seem to be answering back, I'd like help in understanding the code, which runs. Won't name the guy, because that sounds a little mean. The question is to sort a list of filenames based on extension.

After splitting each list member by '.', which just forms a nested list, i think.

# using while loop on list and splitting it
 i=0
    while(i<len(x)):
         x[i]=x[i].split('.')
         i=i+1

He writes this:

x.sort(key=lambda x:x[1])

how does sort() know when key = x[1], it means x[1] of EACH sublist(which should be written as x[][1]) and not just the parent list?

gustoth
  • 1
  • 3

1 Answers1

0

The x in the lambda expression is just an argument passed to it from the elements in the list.

The lambda is equivalent to defining a method to return the second element in the sublists.

def extension_value(x):
    return x[1]

x.sort(key=extension_value)

Python docs explain further:

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

More examples of sorting lists using key functions here.

Alex
  • 509
  • 4
  • 8