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>You are replacing the value of newList on each iteration in the for loop. Hence, after the for loop ends, the value of newList is equal to the sorted value of the last list in the original nested list. Do this:</p>

<pre><code>&gt;&gt;&gt; list = [[3,2,1],[8,7,9],[5,6,4]]
&gt;&gt;&gt; newlist = map(sorted, list)
&gt;&gt;&gt; newlist
[[1, 2, 3], [7, 8, 9], [4, 5, 6]]
</code></pre>

python python-2.7