0

I thought this would be a super simple sorting exercise but I'm not understanding the errors I'm getting.

I'm creating a simple Book class and then adding two entries. I am then sorting via sorted and using a lambda so that I sort by the isbn attribute.

books = []
class Book:
    def __init__(self, title, author, isbn):
        self.title, self.author, self.isbn = title, author, isbn

    def __repr__(self):
        return repr((self.title, self.author, self.isbn))


#add 2 items
b = Book('Russian for All', 'Chompsky', '334')
books.append(b)

c = Book('English for All', 'Zöd', '229')
books.append(c)

#sort items by the isbn number
sorted_books = sorted(books, key=lambda book: book[2])

a) I believe that __repr__ is needed so that a get a nice looking tuple for each entry when adding it to the array, as such:

print(books)
[('Russian for All', 'Chompsky', '334'), ('English for All', 'Zöd', '229')]

b) Because this looks like a standard list of tuples, using the sorted function should function without issue, but alas I get this error:

Traceback (most recent call last):
  File "Untitled 2.py", line 19, in <module>
    sorted_books = sorted(books, key=lambda book: book[2])
  File "Untitled 2.py", line 19, in <lambda>
    sorted_books = sorted(books, key=lambda book: book[2])
TypeError: 'Book' object does not support indexing

It's as if I'm seeing a nice tuple representing the objects but they're actually masking as objects which can't be accessed by the sorting function.

2
  • "Because this looks like a standard list of tuples, using the sorted function should function without issue" - no, you've just changed what your objects look like. You haven't changed anything else about them. Commented Sep 19, 2016 at 23:58
  • 2
    "Because this cyanide pill looks like medicine, I should be able to use it to cure my illness." "Because this counterfeit bill looks like legitimate money, I should be able to purchase things with it without issue." "Because this scam website looks like my bank's website, it should be safe to enter my username and password." Changing what a thing looks like doesn't automatically change what it is or how it behaves. Commented Sep 20, 2016 at 0:05

1 Answer 1

1

No, you need to use:

sorted_books = sorted(books, key=lambda book: book.isbn)

The result:

In [2]: sorted_books = sorted(books, key=lambda book: book.isbn)

In [3]: sorted_books
Out[3]: [('English for All', 'Zöd', '229'), ('Russian for All', 'Chompsky', '334')]

You need to access the book object attribute isbn. The __repr__ is just that, a string representation for printing.

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

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.