In line.split('+')[-1] what does the -1 in the square brackets indicate in Python
The line of code you gave is basically doing three things:
It takes the string
line
and splits it on+
's usingstr.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'
>>>