AlexisSanti
AlexisSanti

Reputation: 15

How can I turn this function into Lambda?

I'm trying to turn this function into a one line function for assignment purposes.

def counter(list_to_count, char_to_count):
    ocurrences_list = []
    for i in list_to_count:
        x = i.count(char_to_count)
        ocurrences_list.append(x)
    return ocurrences_list

This function takes a list of strings and counts the ocurrences of "char" in each element, then makes a list with the amount of ocurrences of "char" per element.

Upvotes: 0

Views: 53

Answers (2)

Guilherme Correa
Guilherme Correa

Reputation: 594

You can simply use a list comprehension to achieve your goal, but if you really want to turn it into a lambda function, just use:

f = lambda list_to_count, char_to_count: [elem.count(char_to_count) for elem in list_to_count]

Upvotes: 0

Barmar
Barmar

Reputation: 780929

Use a list comprehension:

lambda list_to_count, char_to_count: [i.count(char_to_count) for i in list_to_count]

Upvotes: 1

Related Questions