0

What is the difference in below two lines.

I know [::-1] will reverse the matrix. but I want to know what [::] on LHS side '=' does, as without iterating each element how matrix gets reversed in-place in case of 1st case.

  1. matrix[::] = matrix[::-1]
  2. matrix = matrix[::-1]
Zoso7
  • 23
  • 1
  • 5
  • 2
    If you are talking about plain python then there is a good [explanation](https://stackoverflow.com/a/509295/656671) already – Eugene K Mar 04 '18 at 09:19
  • Did you swap them? Because the difference is that the first one _does_ overwrite the original object contents; the second just sets the name to the reversed copy. – Yann Vernier Mar 04 '18 at 09:55
  • Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – nyr1o Mar 04 '18 at 11:50
  • Thanks @YannVernier. I got it now like you said, first one is editing same object and second one is just referencing to new object. – Zoso7 Mar 04 '18 at 16:37

1 Answers1

0

The technic you are looking for called slicing. It is an advanced way to reference elements in some container. Instead of using single index you can use a slice to reference a range of elements.

The slice consists of start, end and step, like this matrix[start:end:step]. You can skip some parts and defaults values will be taken - 0, len(matrix), 1.

Of course, a container must support this technic (protocol).

matrix[::] = # get all elements of the matrix and assign something to them
matrix = # link matrix name with something
matrix[::-1] # get all elements of the matrix in reversed order

So, the first one is actually copying elements in different positions of the same object.

The second one is just linking name matrix with new object constructed from slice of matrix.

Eugene K
  • 388
  • 2
  • 9
  • Thanks Eugene. Below clarification solved my doubt. "So, the first one is actually copying elements in different positions of the same object. The second one is just linking name matrix with new object constructed from slice of matrix." – Zoso7 Mar 04 '18 at 16:31