2

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

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
deep
  • 686
  • 4
  • 17
  • 33

4 Answers4

6

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.

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
3

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.

Sait
  • 19,045
  • 18
  • 72
  • 99
1

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.

Community
  • 1
  • 1
user3636636
  • 2,409
  • 2
  • 16
  • 31
0

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.

Simon
  • 10,679
  • 1
  • 30
  • 44