GeorgeAnghel114
GeorgeAnghel114

Reputation: 73

List comprehension with tuples

list_of_tuples = [(2, 4), (3, 3), (4, 2)]

def my_function(list_of_tuples):
  best = list_of_tuples[0]
    for r in list_of_tuples:
        if r[0] * r[1] > best[0] * best[1]:
            best = r
    return best

I want to write the above function in one line and this is my result

return [i for i in rectangles if i[0] * i[1] > list_of_tuples[0][0] * list_of_tuples[0][1]]

The problem is that I don't know how to write that part with best = r. How can I achieve this?

Upvotes: 1

Views: 968

Answers (2)

BrokenBenchmark
BrokenBenchmark

Reputation: 19223

You can use operator.mul() and functools.reduce() to get the product of every element in each tuple, and then you can take the tuple with the maximum product using max().

Tim Roberts's answer is good for when you only have tuples of size two, but this approach can be used for tuples of arbitrary length (the number of elements in each tuple doesn't even have to be the same!):

from operator import mul
from functools import reduce

max(list_of_tuples, key=lambda x: reduce(mul, x))

Even simpler, you can do:

from math import prod

max(list_of_tuples, key=prod)

by a suggestion from Kelly Bundy.

These output:

(3, 3)

Upvotes: 2

Tim Roberts
Tim Roberts

Reputation: 54698

Python can help you with this:

def my_function(list_of_tuples):
    return max(list_of_tuples, key=lambda k: k[0]*k[1])

Upvotes: 2

Related Questions