1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クイズ形式で学ぶPythonの変数の値の交換や多重代入の注意点

Posted at

クイズ

次のプログラムの出力結果を答えよ。

問1

1
nums = [1, 2, 3]
i = 0
nums[i], i = i, nums[i]

print(nums)
答えを見る [0, 2, 3]

問2

2
nums = [1, 2, 3]
i = 0
i, nums[i] = nums[i], i

print(nums)
答えを見る [1, 0, 3]

多重代入の実行順序

Pythonでは1行で複数の変数に値を代入することができます。

x, y = 0, 1

print(x)  # 0
print(y)  # 1

また、これを利用して、変数の値を交換することができます。

x = 0
y = 1

x, y = y, x

print(x)  # 1
print(y)  # 0

以下のように多重代入を使用せずに値を交換する場合と比べ、新たな変数もいらず、行数も短く済むので便利です。

x = 0
y = 1

temp = x
x = y
y = temp

print(x)  # 1
print(y)  # 0

ただ、今回のクイズのように、単純な交換ではない場合は、実行順序に注意する必要があります。

代入文の右辺の変数の値は、代入文の実行前の値で確定しているのに対し、左辺の変数の値は、左から順に更新されていきます。

問1はこのようなコードでした。

1
nums = [1, 2, 3]
i = 0
nums[i], i = i, nums[i]

print(nums)  # [0, 2, 3]

多重代入の右辺のiの値は0であり、右辺のnums[i]、つまりnums[0]の値は1です。

左辺の変数の値は左から順に更新されていくため、問1は以下のコードと同じことになります。

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]

問2はこのようなコードでした。

2
nums = [1, 2, 3]
i = 0
i, nums[i] = nums[i], i

print(nums)  # [1, 0, 3]

問2は以下のコードと同じことになります。

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]

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?