Jeremy
Jeremy

Reputation: 59

Python: sorting sublist values in nested list

I have a nested list: list = [[3,2,1],[8,7,9],[5,6,4]]

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.

for i in list: newList = sorted[i]

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?

Python version: 2.7.10

OS: OS X El Capitan

Upvotes: 0

Views: 1523

Answers (3)

Adishwar Rishi
Adishwar Rishi

Reputation: 51

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

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

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

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

newSortedList = map(sorted,list) #newSortedList will have all sublists sorted

Upvotes: 0

Nehal J Wani
Nehal J Wani

Reputation: 16619

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:

>>> list = [[3,2,1],[8,7,9],[5,6,4]]
>>> newlist = map(sorted, list)
>>> newlist
[[1, 2, 3], [7, 8, 9], [4, 5, 6]]

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49318

You are creating a new list and assigning it to a new name, then throwing it away. Use the sort method to sort each list reference to in-place. Also note that it doesn't make sense to use a list reference to index the main list, and that you should avoid naming variables with the same name as built-in functions (list in this case).

>>> l = [[3,2,1],[8,7,9],[5,6,4]]
>>> for i in l:
...     i.sort()
...
>>> l
[[1, 2, 3], [7, 8, 9], [4, 5, 6]]

Upvotes: 1

Related Questions