3

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

4
  • How do you want to sort your list? Commented Jul 8, 2015 at 23:29
  • sorted list : [[1,3],[2,6],[8,10],[15,18]] Commented Jul 8, 2015 at 23:33
  • key=operator.itemgetter(0) Commented Jul 8, 2015 at 23:35
  • 1
    Good answers to the question have been posted below. I'd also like to note that the line if intervals == [] : return return [] is unnecessary because [].sort() == [] so the empty list will be returned even without that line. Commented Jul 8, 2015 at 23:41

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.