qarthandso qarthandso - 2 months ago 15
Python Question

Simple Sorting Python Objects - Indexing Error

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.

Answer

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.

Comments