Python: Lambda function to count specific letters in a word and then iterate through a list of words

Question:

I am trying to convert a list comprehension logic to a lambda function. The problem I face is that the function is returning the first value and not iterating through the list.

In this example, I need to return words that contain the max A’s (lower or upper). Here is how I have tried so far

sample list of items -- notice 'armchair' has the max a's

items = ['pillow', 'armchair', 'aloegel', 'hammer']

Wrote a general function (maxa) to return a max item based on count. Note that ‘tally’ is another function I’ve written which works perfectly. ‘Tally’ just returns a count based on certain conditions.

def maxa(tally, items):
    mylist = [(tally(word), word) for word in items]     
    return max(mylist, key = lambda x : x[0])[1] 

I am now trying to replace the function ‘tally’ with a lambda function. This is what I have written so far and returns just the first word in the list. This returns ‘pillow’ instead of ‘amrchair’ so I assume this is somehow not looping. What am I missing?

maxa(lambda x : sum(letter in ('a', 'A') for letter in word), items)

Asked By: Ziba Joon

||

Answers:

Just updating the question with @Barmar ‘s answer (which worked perfectly)

maxa(lambda x : sum(letter in (‘a’, ‘A’) for letter in x), items)

Answered By: Ziba Joon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.