I usually use Python as one of my main programming languages.
I observed that swapping rows of numpy 2d-array by a simultaneous assignment overwrites the elements. What I felt to be odd is this overwrite only happened for:
- 2d-array
and, did not happen for:
- list_of_list
- list_of_array
- array_1d
- list_of_numbers
(Please refer a following "Case 1" result.)
I want to know the mechanism of this behavior. Here is my test code:
import numpy as np
def swap(seq):
'''swaps first two elemnts'''
print('Before swapping\n', seq)
seq[0], seq[1] = seq[1], seq[0]
print('After swapping\n', seq)
print('')
print('Case 1: array_2d')
array_2d = np.arange(8).reshape(4, 2)
swap(array_2d)
print('Case 2: list_of_list')
list_of_list = [[0, 1], [2, 3], [4, 5], [6, 7]]
swap(list_of_list)
print('Case 3: list_of_array')
list_of_array = [np.array([0, 1]),
np.array([2, 3]),
np.array([4, 5]),
np.array([6, 7])]
swap(list_of_array)
print('Case 4: array_1d')
array_1d = np.arange(4)
swap(array_1d)
print('Case 5: list_of_numbers')
list_of_numbers = list(range(4))
swap(list_of_numbers)
Results are:
Case 1: array_2d
Before swapping
[[0 1]
[2 3]
[4 5]
[6 7]]
After swapping
[[2 3] # <- failed to swap
[2 3] # <- failed to swap
[4 5]
[6 7]]
Case 2: list_of_list
Before swapping
[[0, 1], [2, 3], [4, 5], [6, 7]]
After swapping
[[2, 3], [0, 1], [4, 5], [6, 7]]
Case 3: list_of_array
Before swapping
[array([0, 1]), array([2, 3]), array([4, 5]), array([6, 7])]
After swapping
[array([2, 3]), array([0, 1]), array([4, 5]), array([6, 7])]
Case 4: array_1d
Before swapping
[0 1 2 3]
After swapping
[1 0 2 3]
Case 5: list_of_numbers
Before swapping
[0, 1, 2, 3]
After swapping
[1, 0, 2, 3]
I found following posts related to simultaneous assignment, but still can not understand the above behavior.
A solution using .copy()
method.
Assessment order of the simultaneous assignment.
I'm great appreciate for any kind of hints.
Thanks.