What code do?

can somebody please explain to what this functions dose and why…?
def first_plus_last(lst):
return lst[0] + lst[-1]

Python is a language that relies heavily on indentation to indicate code blocks, and due to the way forums posts work, indentation is not preserved when you simply copy/paste code.
In this case it is obvious how your code is supposed to be indented, but in a large program it may not be so easy.

Fortunately the forums allow you to format your code, to preserve indentation. Simply press this button:

And then copy/past your code between the two rows of backticks:


Well the name of this function describes its self rather well:

def first_plus_last(lst):

Have you learned about string slicing yet?

In this example:

lst = [3, 4, 5]
a = lst[0]
b = lst[-1]

What is the value of a?
How about b?
Try adding the two together.

Try printing out the value of the function with a list parameter.
You’ll see it is returning the values of the first element in the list added to the last element in the list.

3 Likes