Search code examples
pythonlistmultiplication

How to sort a list of lists based on multiplication of elements inside of smaller list


How do I sort list of lists based on product of multiplication of elements in list?

list1 = [[11,11], [15,12], [13,18], [14,21]...[a,b]]

How do i sort list from the smallest value of a*b to the highest? Let's say we have list2 = [[1,1], [5,5], [2,2]], and i want it to be sorted based of [a,b] inside of a big list so the outcome would be:

list3 = [[1,1], [2,2], [5,5]]

I kinda tried something like list1.sort[key = a * b] but it does not work and i don't really know how to take up on this problem


Solution

  • I unsorted your input list so you can see the result is different:

    inputs = [[15,12], [13,18], [14,21],[11,11]]
    
    results = sorted(inputs,key=lambda x:x[0]*x[1])
    
    print( f"{results=}" )
    

    result:

    results=[[11, 11], [15, 12], [13, 18], [14, 21]]