2

This is the list I started with

names = ["Alice", "Beatrice", "Amarnae", "Zootrope"]

The last three items all have 4 vowels each

Created a sorted list based on the count of vowels. Got the one shown below

mylist = [(3, 'Alice'), (4, 'Amarnae'), (4, 'Beatrice'), (4, 'Zootrope')]

I need to return/find the 1st occurrence of the max quantity

print(max(mylist))

which returns

(4, 'Zootrope')

Ask: I need to return as that is the first occurrence of the name in the original list

(4, 'Beatrice')

I have tried a few different things (incl. mylist.sort(key = lambda x: (x[0], x[1]) .. but doesn't seem to work.

gaurav8936
  • 43
  • 7
  • "I have tried a few different things (incl. mylist.sort(key = lambda x: (x[0], x[1]) .. but doesn't seem to work." That's how it's done. If you have a [debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) question, [after taking your own best shot at it first](https://meta.stackoverflow.com/questions/261592), show us exactly what code you have, explain what happened and what you expect should happen instead, using a [mre] (in a new question). – Karl Knechtel Sep 23 '22 at 05:41
  • "I need to return as that is the first occurrence of the name in the original list" Python's sort is stable, so the results would naturally be in this order. However, `max` and `sort` are not related. – Karl Knechtel Sep 23 '22 at 05:43

1 Answers1

3

Your mylist is not created with the original item order retained in the first place, hence the issue.

You can use a list comprehension like this to create mylist:

mylist = [(sum(c in 'aeiou' for c in name.lower()), name) for name in names]

which results in the following value for mylist, retaining the original item order:

[(3, 'Alice'), (4, 'Beatrice'), (4, 'Amarnae'), (4, 'Zootrope')]

Since max returns the first item with the maximum value, you can then simply use max with a key function that returns just the first item in the tuple for comparison, since you don't want the lexicographical order of the second item to be taken into account:

max(mylist, key=lambda t: t[0])

which returns:

(4, 'Beatrice')

Demo: https://replit.com/@blhsing/SwelteringFlakyDividend

blhsing
  • 91,368
  • 6
  • 71
  • 106