Simple Sorting Python Objects - Indexing Error
<p>I thought this would be a super simple sorting exercise but I'm not understanding the errors I'm getting.</p>

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

<pre><code>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])
</code></pre>

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

<pre><code>print(books)
[('Russian for All', 'Chompsky', '334'), ('English for All', 'ZÃ¶d', '229')]
</code></pre>

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

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

<p>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.</p>

<p>No, you need to use:</p>

<pre><code>sorted_books = sorted(books, key=lambda book: book.isbn)
</code></pre>

<p>The result:</p>

<pre><code>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')]
</code></pre>

<p>You need to access the book object attribute <code>isbn</code>. The <code>__repr__</code> is just that, a string representation <em>for printing</em>.</p>

python sorting