Python has the function slice
, but I believe that the most simplified way of if you extract an element set, you must use the same notation to get a single element: lista[<Índice>]
, but you must enter the desired range: lista[<Inicio>:<Fim>]
input = [ 'laranja', 'limão', 'melancia', 'mamão' ]
print(input[1:-1])
Example online repl.it
Continuing the same notation above, there is the third parameter that is the step : lista[<Inicio>:<Fim>:<Passo>]
, the step has its initial value as 1 >, and if you enter the 0 value, an exception will be released like this:
Traceback (most recent call last):
File "python", line 3, in <module>
ValueError: slice step cannot be zero
Example with step :
numeros = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numeros[::2]) # Impares
print(numeros[1::2]) # Pares
Example online repl.it
Example using the slice
function.
input = [ 'laranja', 'limão', 'melancia', 'mamão' ]
print(input[slice(1,-1)])
Example online repl.it
Example using step 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
Example online repl.it