Question
In the context of this exercise, how does the lambda function in the example work?
Answer
In this exercise, the lambda function given in the example was
lambda x: x.split('@')[-1]
A quick explanation of what this lambda function will do is, it will take in a string input value, which will be an Email address like "[email protected]"
, and return the Email provider, "gmail.com"
.
To better understand how it accomplishes this, let’s work through each part:
First, it will use .split()
to “split” the inputted string on the delimiter '@'
. In Python, this will return a new list with the string split into substrings separated on any "@"
which were in the string. So, given
x = "[email protected]"
x.split('@')
returns the list
['john.smith', 'gmail.com']
Finally, the function will access the last element of this list, using index -1
. If you recall, we can use negative index values to select elements from the last position, where -1
selects the last element, -2
selects the second to last, and so on.
# x = "[email protected]"
x.split('@')[-1]
# = ['john.smith', 'gmail.com'][-1]
# = 'gmail.com'