How does the lambda function in the example work?



In the context of this exercise, how does the lambda function in the example work?


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 "", and return the Email provider, "".

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 = ""

returns the list
['john.smith', '']

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 = ""

# = ['john.smith', ''][-1]
# = ''