Vowel List: weird lambda expression… here is a solution to the problem.
Vowel List: weird lambda expression
Can someone explain why the code below produces a list of vowels? It seems like the lambda expression should only look at the first letter of the string, but it somehow collects all the characters in the string that are in “aeiou”:
nameFull = input("Please enter your name: ")
nameBroken = nameFull.split()
print(list(filter(lambda x: x[0] in "aeiou", nameFull)))
#(i.e. if nameFull = hello, ["e", "o"] is the result)
Solution
Passing nameFull
to filter
causes each individual character of the string to be sent as an x
to the lambda
>. The [0]
inside is redundant and not necessary; It just grabs the first character of x
, which is already a single-character string. For readability, you should probably remove it.
Here’s a demo:
>>> nameFull = input("Please enter your name: ")
Please enter your name: Robert
>>>
>>> print(list(filter(lambda x: x in "aeiou", nameFull))) # Works fine without [0].
['o', 'e']
>>>
>>> 'a'[0] # [0] does nothing.
'a'
>>> 'a'[0] == 'a'
True
>>>