Xantium
Xantium

Reputation: 11605

Sorting a list of lists in a list

Say I have a list inside a list, that is contained inside a list. For example:

foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

And I wanted to sort it in order:

foo = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

I could use [sorted(i) for i in foo] to achieve this. However is there some way to sort this list without list comprehension (or creating a new list)?

The values inside the lists themselves will change but do not need to be sorted.

Everything I have tried just boils down to the same method as above.

Upvotes: 4

Views: 312

Answers (2)

flamenco
flamenco

Reputation: 2840

If you don't mind creating a new list, how about using map function:

In [1]: foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

In [2]: list(map(sorted, foo))
Out[2]: [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

Upvotes: 3

AlanK
AlanK

Reputation: 9833

If you want to avoid creating a new list, then just iterate over the lists and call .sort()

>>> foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

for i in foo:
    i.sort()

>>> foo                                                                         
[[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

Upvotes: 6

Related Questions