Reputation: 3677
I have two lists l1 and l2:
l1 = [x,y,3,4,5]
l2 = [x,y,30,1,2]
I want to make a list l3 which is the list that has the maximum in the 3rd element of the list (in the above example it would be 3 in l1 and 30 in l2). In the above case l3 = [x,y,30,1,2] How can I do this?
Upvotes: 1
Views: 478
Reputation: 180540
You can use a simple if/else
considering you are just comparing two elements:
l3 = l1 if l1[2] > l2[2] else l2
But beware you are creating a reference not a copy.
If you want a new list you need to copy:
l3 = l1[:] if l1[2] > l2[2] else l2[:]
If you don't copy any changes to in this case l2
as it has the larger third element will be reflected in l3 and vice-versa.
Also if you have other mutable objects in the list you will need to make a copy.deepcopy
:
from copy import deepcopy
l3 = deepcopy(l1 ) if l1[2] > l2[2] else deepcopy(l2)
Upvotes: 1
Reputation: 118021
You can use the key
argument of max
to get the list with the larger element [2]
l3 = max((l1, l2), key = lambda i: i[2])
Upvotes: 4