Sort a list of objects based on second value of list attribute
<p>I have a list of Car objects, each object being defined as follows:</p>

<pre><code>class Car:
    def __init__(self, vin, name, year, price, weight, desc, owner):
        self.uid = vin
        self.name = name
        self.year = year
        self.price = price
        self.weight = weight
        self.desc = desc
        self.owner = owner
        self.depreciation_values = self.get_depreciation_values(name, vin)
</code></pre>

<p>The depreciation_values attribute is a list that has 8 components, like below:</p>

<pre><code>[-12.90706937872767, -2.2011534921064739, '-17', '-51.52%', '-7', '-2.75%', '-5', '-1.74%']
</code></pre>

<p>The second value (-2.2011534921064739) denotes the depreciation factor and is what I'm trying to use as the sort key.</p>

<p>I'm aware of attrgetter:</p>

<pre><code>car_list.sort(key=attrgetter('depreciation_values'))
</code></pre>

<p>But this would sort the list based on the first value of depreciation_values and not the second.</p>

<p>Is there a way to sort all the objects based on the depreciation factor?</p>

<p>You could define a <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="nofollow"><code>__lt__()</code> (less than) method</a> and other comparison methods to return a boolean based on your desired sort attribute then you could use the built-in sorted() or <code>list.sort()</code>. <a href="https://docs.python.org/3/howto/sorting.html#odd-and-ends" rel="nofollow">"... sort routines are guaranteed to use <code>__lt__</code>() ... "</a></p>

<pre><code>class Car:
    ...
    def __lt__(self, other):
        self.depreciation_values[1] &lt; other..depreciation_values[1]
</code></pre>

python sorting