How to display elements of specific sizes belonging to a list using lambda and filter functions?

Asked

Viewed 24 times

-1

In that code I wrote:

lstNomes = ["casa", "google", "escola"]

lstFiltro = list(filter(lambda x: x <= "5", lstNomes))

Is returning the empty array:

[]

I wanted to know how I get the element inside the lstNomes with length less than or equal to 5.

1 answer

0


To resolve this issue, just use the following code:

lstNomes = ["casa", "google", "escola"]

lstFiltro = list(filter(lambda x: len(x) <= 5, lstNomes))
print(lstFiltro)

Observation 1:

How you want to capture words of size less than or equal to 5 and, as the elements of the list are strings, you should check the size of each iterated element, then display them.

Observation 2:

In this case it was displayed only 1 result. Because in this case, we only have one word of size less than or equal to 5.

Now, if there were other words in this list of sizes less than or equal to 5, all of them would be shown.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.