Why when using:
Lista[:: -1]
In Python this reverses the string, so what does it mean ::
? . A very explicit answer that explains well the ins and outs of what this does would be very good...
Why when using:
Lista[:: -1]
In Python this reverses the string, so what does it mean ::
? . A very explicit answer that explains well the ins and outs of what this does would be very good...
Lists and strings support the slice operator , the general syntax of which is
[inicio:fin:paso]
. For example list[3:20:4]. This causes the sublist composed of the elements [3], [7], [11], [15] and [19] to be extracted. In general, we start with the indexinicio
, and we addpaso
.fin
When or greater is reached , it is no longer fetched ([fin]
it will never be part of the fetched sublist).All three parameters are optional:
If you omit
paso
, it is considered 1. Then itlista[3:20]
would extract all elements between 3 and 19, inclusive.If you omit
inicio
it is considered 0. Then itlista[:5]
would extract elements 0 to 4 inclusive. Or put another way "the first 5 elements".If you omit
fin
, the length of the list plus 1 is considered. That is,lista[5:]
it will return the sublist with elements 5, 6, etc. up to the last (inclusive).If you omit all three, you have the syntax
Lista[:]
that returns a copy of the entire list, since start is considered 0, end is considered the last element (inclusive), and step is considered 1.This option may seem silly or useless. Why do
a = b[:]
being able to doa = b
? The reason is that the second assignment doesn't make a copy, it just makesa
it refer to the same list it was referring tob
, but only one list exists, with "two names" so to speak. Instead ita = b[:]
creates a copy of the elements ofb
in a new list, anda
refers to the new list. They are two different objects. Equivalent toa = b.copy()
.On the other hand, the step can be negative, which implies that it
inicio
should be greater thanfinal
. Thus, for exampleLista[10:3:-2]
, it would start with the index 10 and go down through 8, 6, 4, and there it would stop because the next (2) is already less than or equal tofin
(3).In the case where step is negative, then the omission of de
inicio
andfin
has a slightly different meaning.inicio
will be considered equal to the length of the list, andfin
the first element will be considered (inclusive).So it
Lista[::-1]
starts at the last index in the list, goes back one at a time, and ends at the first (0). That is, it returns the same list but "in reverse".As you can see
::
, it is not a special operator itself, it is just that they have been omittedinicio
fromfin
the slice syntax . It is necessary to leave the gaps, because if we put for exampleLista[-1]
orLista[:-1]
not it would be clear that -1 refers to the "step", hence the two::
.