0

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

1
  • Replace the body of the loop with i.sort(). That sorts the (sub)list in-place. Commented Sep 11, 2016 at 2:51

3 Answers 3

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

1

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]]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.