Is there any pythonic way to slice an array?

7

In JavaScript there is Array.prototype.slice :

var input = [ 'laranja', 'limão', 'melancia', 'mamão' ];

var aparada = input.slice(1, -1);

console.log( aparada );

And in PHP array_slice :

$input = array( 'laranja', 'limão', 'melancia', 'mamão' );

print_r( array_slice($input, 0, -1) );

How could I do this in Python in a simplified way?

    
asked by anonymous 24.12.2017 / 20:00

1 answer

4

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

    
25.12.2017 / 05:43