What is [:: - 1] in Python?

1

I would like to know in the following code:

    import sys 

if len(sys.argv) == 2:
    numero = sys.argv[1][::-1]
    longitud = len(numero)

    for i in range(longitud):
        print('{:0{}d}'.format(int(numero[i]) * 10 ** i, longitud))

else:
    print('Error, número de argumentos no válido')
    print('Ejemplo: python descomposicion.py [numero]') 

What is the function of this:

  

[:: - 1]

and in what situations it is used, thank you!

    
asked by Melissa Alvarez 28.11.2018 в 17:41
source

1 answer

4

The [::-1] is a "trick" often used in python to get a list or string "inside out". It is based on the slice operator (slice) whose general syntax is:

iterable[inicio:fin:paso]

that allows you to extract a series of elements from the iterable , starting with the numbered as inicio and ending with the numbered fin-1 , increasing from paso in paso .

If you omit inicio it will start at the first iterable element, if you omit fin it will end at the last iterable element.

If the paso is negative, the iterable is traversed "backward", and in that case the default values when omitting inicio and fin are reversed.

So iterable[::-1] returns the elements of the iterable, starting with the last one and ending with the first, in reverse order as they were.

    
answered by 28.11.2018 / 17:56
source