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:

  1. 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']
    >>>
    
  2. The [-1] then indexes that list at position -1. Doing so will return the last item:

    >>> ['a', 'b', 'c', 'd'][-1]
    'd'
    >>>
    
  3. 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'
>>>

Tags:

Python

Syntax