Python: sorting sublist values in nested list
<p>I have a nested list:
<code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p>

<p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p>

<p><code>for i in list:
    newList = sorted[i]</code></p>

<p>So for this example the for loop would loop through the whole list, but only sort the last sublist [5,6,4]. How do I make it sort all the sublists?</p>

<p>Python version: 2.7.10 </p>

<p>OS: OS X El Capitan</p>

<p>The reason your code is not working is because you are creating a new sorted list (<code>sorted()</code> creates a new list) and assigning it to a variable (<code>newList</code>). This variable goes unused.</p>

<p>Python lists have a <code>.sort()</code> method. So your loop code can work as follows</p>

<pre><code>for sublist in list:
    sublist.sort() #sorts the sublist in place
print list #all sublists will be sorted in ascending order
</code></pre>

<p>As mentioned by Nehal J Wani, you can also use a map to apply one function to each element of a list.</p>

<pre><code>newSortedList = map(sorted,list) #newSortedList will have all sublists sorted
</code></pre>

python python-2.7