How does the lambda function in the example work?

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 "john.smith@gmail.com", 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 = "john.smith@gmail.com"

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 = "john.smith@gmail.com"

x.split('@')[-1]
# = ['john.smith', 'gmail.com'][-1]
# = 'gmail.com'
6 Likes

2 posts were split to a new topic: Correct result but the program would not accept

3 posts were split to a new topic: Why it’s the same outcome

2 posts were split to a new topic: Why we should use [-1]