In line.split('+')[-1] what does the -1 in the square brackets indicate in Python

python, syntax

Solution

The line of code you gave is basically doing three things:

It takes the string `line` and splits it on `+`'s using `str.split`. This will return a list of substrings:

>>> line = 'a+b+c+d'
>>> line.split('+')
['a', 'b', 'c', 'd']
>>>

The `[-1]` then indexes that list at position `-1`. Doing so will return the last item:

>>> ['a', 'b', 'c', 'd'][-1]
'd'
>>>

It takes this item and assigns it as a value for the variable `name`.

Below is a more complete demonstration of the concepts mentioned above:

>>> line = 'a+b+c+d'
>>> line.split('+')
['a', 'b', 'c', 'd']
>>> lst = line.split('+')
>>> lst[-1]
'd'
>>> lst[0]
'a'
>>> lst[1]
'b'
>>> lst[2]
'c'
>>> lst[3]
'd'
>>>

Problem

Let's assume that we have this code: ``` name = line.split('+')[-1] ``` What does the -1 do? I have seen it in various codes but not sure on what it does? And what would the difference be if there was a `[0]` or a `[1]`?

Original source