4

I have two lists of numbers and I want a function to return the list with the largest number i.e with two lists [1,2,3,9] and [4,5,6,7,8], the function should return [1,2,3,9].

I know for a fact that this works:

a = [1,2,3,9]
b = [4,5,6,7,8]
ans = [_ for _ in [a,b] if max(_) == max((max(a),max(b)))][0]

I know that there is:

a = [1,2,3,9]
b = [4,5,6,7,8]
if max(a)>max(b):
    ans = a
else:
    ans = b

But is there a more efficient one or two line solution?

4 Answers4

9

How about using the following without any for loop. Just compare the max of lists

a = [1,2,3,9]
b = [4,5,6,7,8]
ans = (a if max(a) > max(b) else b)
# [1, 2, 3, 9]
Sheldore
  • 32,099
  • 6
  • 34
  • 53
  • 1
    Thanks for the speedy reply. Can you explain why the result isn't a tuple even though you put it in brackets? – Wan-Hew Tran Mar 27 '19 at 23:29
  • 2
    @w it returns `a` if max(a) > max(b) else it returns`b`. A tuple is create by `(a,)` - see [ternary operator](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – Patrick Artner Mar 27 '19 at 23:31
3

The max function allows you to specify a key. You can supply the two lists as a list of lists to max() and use max as the key function. This will give yout the result with a very compact statement:

a = [1,2,3,9]
b = [4,5,6,7,8]
result = max([a,b],key=max)
Alain T.
  • 24,524
  • 2
  • 27
  • 43
0

This would work

max([a,b], key=max)

The trick here is to know that the max function can be applied to objects which do not have a natural numerical interpretation, using a key function.

Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
Jon Kiparsky
  • 6,854
  • 2
  • 20
  • 37
0

I would recommend numpy or pandas but your solution looks good to be honest.

Here is a numpy example (typing on phone so not tested)

npa = np.array(a) 
npb = np.array(b)

max_array = None
total_max = 0  # or -np.inf if you want to deal with negative numbers too
for k in [npa, npb]:
    if k.max() > total_max:
         max_array = k
Jurgen Strydom
  • 2,390
  • 19
  • 29