Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
Xantium Avatar asked Jan 03 '23 03:01

Xantium


1 Answers

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]]]
like image 107
AK47 Avatar answered Jan 08 '23 13:01

AK47