Can anyone help me understand this line of code?

I am on Splitting Strings II task 2 (https://www.codecademy.com/courses/learn-python-3/lessons/string-methods/exercises/splitting-strings-ii)

The code:

uthor_last_names = [] for name in author_names: author_last_names.append(name.split()[-1])

What i don’t understand is the last line of the code, why are there two brackets facing each other? I don’t feel like I’ve seen or learnt about this in the python 3 course before. Could anyone help with understanding this?

It looks like you want to access the last element of a list? If so, the [-1] is another way of saying the last element in a list.

If you are referring to the the actual brackets in the last line, then ethano is correct. The code is using an index on the list created by split.

If you’re asking about the parenthesis after split … so name.split() split is a method that can be be done by all string objects. So the proper syntax to call that method is string.split(). If you leave the parameters empty the default split is all white space … so spaces, tabs, returns, etc. Or you can specific the split by adding a parameter.

So in the case of the last line, it’s taking the name variable, split it on all white space characters, which creates a list. And then using the [-1] to take the last element of that list.

Hope that helps.

1 Like

I understand now, thanks :smiley: