0

Straight to the point. The next statements have the effect of swapping the contents of the two list elements of the python 2D-list:

a = [[1,2,3],
     [4,5,6]]
b = [[7,8,9],
     [10,11,12]]

tmp = a[1]
a[1] = b[1]
b[1] = tmp

output:

a = [[1,2,3],
     [10,11,12]]

b = [[7,8,9],
     [4,5,6]]

For the numpy array type this would not have happened.

a = np.array([[1,2,3],
              [4,5,6]])
b = np.array([[7,8,9],
              [10,11,12]])

tmp = a[1]
a[1] = b[1]
b[1] = tmp

output:

a = array([[ 1,  2,  3],
           [10, 11, 12]])

b = array([[ 7,  8,  9],
           [10, 11, 12]])

Why is that so?

1 Answer 1

3

The list of lists are nested objects. The NumPy array is not nested but 2D. There is no notion of 2D with lists. So you have a list in a list. Whereas in NumPy it is just one object.

NumPy always returns a view when indexing and the result of indexing is another array. You need to make explicit copies:

tmp = a[1].copy()
a[1] = b[1].copy()
b[1] = tmp

to get it swapped:

>>> a
array([[ 1,  2,  3],
       [10, 11, 12]])
>>> b
array([[7, 8, 9],
       [4, 5, 6]])

Rule of thumb:

  1. Indexing of list in list == reference to sub-list
  2. Indexing of NumPy 2D array along first dimension == view, i.e. shared data
Sign up to request clarification or add additional context in comments.

4 Comments

Slicing a list produces a shallow copy, but indexing does something even shallower, sometimes referred to as a "reference copy" or "not a copy".
@user2357112 You are right. Improved my answer accordingly.
@user2357112 could you please elaborate on that a little more. As I understand this, a reference copy is some kind of a shallow copy (a shallow copy that can and will change the actual object if changed, i.e. not a lazy copy). So why do you make it sound like they are two different things? Am I missing something?
@Lockon2000: Slicing a list produces a new list object with references to the same elements the original list had references to. Indexing a list doesn't produce any new objects at all; it just gives you a reference to the object the corresponding list cell had a reference to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.