Bret
Bret

Reputation: 81

Is there a way to sort nested lists in Python 3+?

I am working with nested lists, and I am wondering how to alphabetize all lists while keeping them contained in their respective lists.

For example, if I had a nested lists that contained brand names:

lst = [['Canada Goose', 'Mackage', 'PJ'], ['GAP', 'Fendi', 'Nike'], ['Gucci', 'Adidas']]

And its output:

sorted_lst = [['Canada Goose', 'Mackage', 'PJ'], ['Fendi', 'GAP', 'Nike'], ['Adidas', 'Gucci']]

I know that in regular lists you can use the .sort() method however here that doesn't seem to be the case. I also read Sorting lists inside nested lists and I don't seem to understand

Upvotes: 2

Views: 76

Answers (2)

kaya3
kaya3

Reputation: 51034

AppHandwerker's solution creates a new data structure to hold the result, leaving the original lst unchanged. If that's a requirement, then that solution is best. It's also generally a good idea to avoid mutation, since it can lead to subtle bugs caused by aliasing.

In case you don't need to keep the original data in its unsorted order, here's an in-place solution as an alternative: the advantage of sorting in-place is that it doesn't require additional memory to be allocated for the new lists holding the sorted results.

for x in lst:
    x.sort()

Upvotes: 3

AppHandwerker
AppHandwerker

Reputation: 1788

As commented by @SyntaxVoid

sorted_lst = [sorted(x) for x in lst]

Should do what you are asking.

To be clear what is going on here, is your are generating a new list of sorted lists using a generator.

[] this as you know is a list

and approximitley what is done above is similar to writing

    sorted_lst = []
    for x in lst:
        sorted_lst.append(sorted(x)) 

You should read https://realpython.com/python-sort/ for more help and to understand how sort and sorted work.

In addition to better understand SyntaxVoid's answer I would suggest you google Python Generator, as my explination is an apprimate example and doesn't explain the underlying deifference between my explination and the code, namely that one generates a d generator the other a list.

Upvotes: 2

Related Questions