Answer the output of the following program.
1
nums = [1, 2, 3]
i = 0
nums[i], i = i, nums[i]
print(nums)
2
nums = [1, 2, 3]
i = 0
i, nums[i] = nums[i], i
print(nums)
Python allows you to assign values to multiple variables on a single line.
x, y = 0, 1
print(x) # 0
print(y) # 1
You can also use this to exchange the values of variables.
x = 0
y = 1
x, y = y, x
print(x) # 1
print(y) # 0
Compared to exchanging values without using multiple assignment as shown below, it is convenient because it does not require new variables and the number of lines can be shortened.
x = 0
y = 1
temp = x
x = y
y = temp
print(x) # 1
print(y) # 0
However, if it is not a simple exchange like this quiz, you need to pay attention to the execution order.
The value of the variable on the right side of the assignment statement is fixed by the value before execution of the assignment statement, while the value of the variable on the left side is updated in order from the left.
Question 1 was such a code.
1
nums = [1, 2, 3]
i = 0
nums[i], i = i, nums[i]
print(nums) # [0, 2, 3]
The value of i
on the right side of multiple assignment is 0, and the value ofnums [i]
on the right side, that is,nums [0]
is 1.
Since the values of the variables on the left side are updated in order from the left, Question 1 is the same as the code below.
1'
nums = [1, 2, 3]
i = 0
# nums[i], i = i, nums[i]
# => nums[i], i = 0, nums[0]
# => nums[i], i = 0, 1
nums[i] = 0 # => nums[0] = 0
i = 1
print(nums) # [0, 2, 3]
Question 2 was such a code.
2
nums = [1, 2, 3]
i = 0
i, nums[i] = nums[i], i
print(nums) # [1, 0, 3]
Question 2 is the same as the code below.
2'
nums = [1, 2, 3]
i = 0
# i, nums[i] = nums[i], i
# => i, nums[i] = nums[0], 0
# => i, nums[i] = 1, 0
i = 1
nums[i] = 0 # => nums[1] = 0
print(nums) # [1, 0, 3]
-7.2. Assignment statement — 7. Simple statement — Python 3.9.1 Document
Recommended Posts