NIk
NIk

Reputation: 123

How to sort each list in a list of lists

How can I sort the lists in the following nested list? Function sort works only on normal lists.

lst = [[123,3,12],[89,14,2],[901,4,67]]

Expected result:

[[3,12,123],[2,14,89],[4,67,901]] 

Upvotes: 8

Views: 1210

Answers (4)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

Here's a functional way to achieve this using map() with sorted() as:

>>> lst = [[123,3,12],[89,14,2],[901,4,67]]

>>> list(map(sorted, lst))
[[3, 12, 123], [2, 14, 89], [4, 67, 901]]

To know more about these functions, refer:

Upvotes: 6

quamrana
quamrana

Reputation: 39354

Just sort each sub list independently:

lst = [[123,3,12],[89,14,2],[901,4,67]]
lst = [sorted(sub) for sub in lst]

Upvotes: 5

Stefan
Stefan

Reputation: 957

This is a very straightforward way to do it without any packages (list comprehension)

lst_sort = [sorted(item) for item in lst]

Upvotes: 12

Jack Dane
Jack Dane

Reputation: 402

try this:

lst = [[123,3,12],[89,14,2],[901,4,67]]

for element in lst:
    element.sort()

print(lst)

Loop through each item and sort separately.

Upvotes: 7

Related Questions