Is there any pythonic way to make "Slice" from an array?

Asked

Viewed 318 times

10

In Javascript there is the Array.prototype.slice:

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

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

console.log( aparada );

And in the PHP the 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 more simplified way?

1 answer

9

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.

  • 2

    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.

  • It makes sense what you said @jsbueno, because at one time or another we would need the Slice.indices method to avoid error handling.

  • @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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.