Python Practice › List Programs › Program 63
Sort sublists by their sum
Write a Python program to sort a list of sublists by the sum of each sublist.
Input
[[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
Output
[[1, 2, 1], [0, 4, 1], [2, 1, 3], [5, 1, 1], [3, 5, 6]]
Approach
sortedwithkey=sum.
Solution
data = [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]print(sorted(data, key=sum))Output
[[1, 2, 1], [0, 4, 1], [2, 1, 3], [5, 1, 1], [3, 5, 6]]
Learn the concept
New to this topic? Read the lesson, then come back.