deep
deep

Reputation: 716

Understanding lambda's sort function in python

I am trying to sort the list of lists in python. I have written the following code:

def sort(intervals):
    if intervals == [] : return []  
    intervals.sort(key = lambda x:x.start)
    return intervals

a = [[1,3],[8,10],[15,18],[2,6]]
print(sort(a))

I am getting the following error:

AttributeError: 'list' object has no attribute 'start'

Please can someone explain lambda function for sort and some details about the above error. Thank you!!

Upvotes: 2

Views: 15309

Answers (4)

Iron Fist
Iron Fist

Reputation: 10951

The reason for your error message is that you are sorting based on an attribute that is not for list (start is not an attribute of a list'), so quick fix is, either to use the sort method of list or use built-in method sorted:

1 - Using sort method of list:

intervals.sort(key = lambda l:l[0])

2 - Using built-in method sorted:

intervals = sorted(intervals, key=lambda l:l[0])

Reading more about sorting list in this wiki post, very interesting.

Upvotes: 6

Simon
Simon

Reputation: 10841

It isn't actually necessary to use a lambda function to sort a list of lists. Take the following example:

a = [[1,3],[8,10],[15,18],[2,6],[2,5]]
print (sorted(a))

... this gives the output:

[[1, 3], [2, 5], [2, 6], [8, 10], [15, 18]]

... thus it not only sorts on the first element of each sub-list but uses the subsequent elements as keys if the first elements of two sublists are equal.

Upvotes: 0

Sait
Sait

Reputation: 19805

You should use:

intervals.sort(key = lambda x:x[0])

lambda is a fast-way of making functions. For example,

def getFirst(x):
   return x[0]

is equal to:

getFirst = lambda x: x[0]

I guess you should read the official documentation.

PS: Be aware that you are making in place sorting. You can also use sorted(a, key=lambda x:x[0]) which returns another copy of sorted array, if you want otherwise.

Upvotes: 3

user3636636
user3636636

Reputation: 2499

The use of lambda creates an anonymous function where x is the parameter. Key is basically assigning the result from this function as the basis for the sort. A much more in depth answer can be found here

But it looks like you are looking for something like this:

intervals.sort(key = lambda x:x[0])

Where x[0] is obviously the first element of each list.

Upvotes: 1

Related Questions