Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding lambda's sort function in python

Tags:

python

lambda

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!!

like image 845
deep Avatar asked Sep 22 '26 22:09

deep


2 Answers

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.

like image 163
Iron Fist Avatar answered Sep 25 '26 11:09

Iron Fist


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.

like image 39
Sait Avatar answered Sep 25 '26 10:09

Sait



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!