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 "[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'
5 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]

I tried to create my new column using

df.last_name = df.name.apply(get_last_name)

but it didn’t work.
Am I right saying I can only create a new column in a dataframe using the df['last_name'] syntax ?
And df.last_name can only be used to invoke an existing column ?

for this purpose in this lesson, yes, you add a new column to a df as you wrote, df['col_name'] = ... b/c the new col is a series.

Summary
get_last_name = lambda x: x.split()[-1]
df['last_name'] = df.name.apply(get_last_name)

Yes.