As a newbie to Python, I understand a, b = b, a
in python as a simple swap, but why does it not behave as I expected when a
and b
are two subarrays with different lengths?
For example:
nums = [1, 2, 3, 4, 5, 6, 7]
nums[0:4], nums[4:] = nums[4:], nums[0:4]
print(nums) #[5, 6, 7, 5, 1, 2, 3, 4]
Why there's a duplicated 5 after 7? Why is it not [5, 6, 7, 1, 2, 3, 4] since I just divided nums
into 2 subarrays and swapped their order?
Thanks!
CodePudding user response:
Thinking of a, b = b, a
as a swap breaks down when you're working with more complicated expressions than just variables.
When evaluating nums[0:4], nums[4:] = nums[4:], nums[0:4]
, Python starts with the RHS, which evaluates to ([5, 6, 7], [1, 2, 3, 4])
.
Then it assigns [5, 6, 7]
to nums[0:4]
. This replaces the first 4 elements of nums
with the elements of the [5, 6, 7]
list, producing
[5, 6, 7, 5, 6, 7]
Then it assigns [1, 2, 3, 4]
to nums[4:]
. nums[4:]
is not the last 3 elements, because the first assignment changed the size of the list. nums[4:]
is now only the last two elements. Python replaces the last two elements of nums
with [1, 2, 3, 4]
, producing
[5, 6, 7, 5, 1, 2, 3, 4]
CodePudding user response:
Do it the other way around and it works:
nums[4:], nums[0:4] = nums[0:4], nums[4:]
# nums is [5, 6, 7, 1, 2, 3, 4]