Python has the function slice
, but I believe that the most simplified way of extracting a set of elements should be to use the same notation to obtain a single element: lista[<Índice>]
, but must inform the desired range: lista[<Inicio>:<Fim>]
input = [ 'laranja', 'limão', 'melancia', 'mamão' ]
print(input[1:-1])
Online example repl it.
Continuing the same notation above, there is the third parameter which is the footstep: lista[<Inicio>:<Fim>:<Passo>]
, the footstep has its initial value as 1, and if informed the value 0 a exception like this:
Traceback (most recent call last):
File "python", line 3, in <module>
ValueError: slice step cannot be zero
Example with footstep:
numeros = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numeros[::2]) # Impares
print(numeros[1::2]) # Pares
Online example repl it.
Example using the function slice
.
input = [ 'laranja', 'limão', 'melancia', 'mamão' ]
print(input[slice(1,-1)])
Online example repl it.
Example using footstep in function slice
.
numeros = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
print(numeros[slice(None,None,2)]) # Impares
print(numeros[slice(1,None,2)]) # Pares
Online example repl it.
the "function"
slice
Python mentioned in the first paragraph is not used as indicated. It only builds an "Slice" object that is used internally to pick up sequence sessions, as explained in the rest of the answer. In general it is only used if you are implementing a sequence class that works as a list.– jsbueno
It makes sense what you said @jsbueno, because at one time or another we would need the Slice.indices method to avoid error handling.
– Franklin Timóteo
@jsbueno thank you for the feedback, I’m kind of a layman at Python, and I confess that I was confused when I found in the documentation about this function, until now create a question about the same: Doubt about the Slice function
– NoobSaibot