LoginSignup
0
0

More than 3 years have passed since last update.

【python】配列の値を入れ替える方法

Posted at

【python】配列の入れ替え

要素の番号をイコールでつなぐことで要素を簡単に入れ替えることができる。

例えば、1~5の整数が入った配列の先頭と末尾を入れ替えたい場合、それぞれの値を左右で入れ替えてイコールでつなげばOK。

a = [1,2,3,4,5]

a[0], a[4] = a[4], a[0]
print(a)

#[5, 2, 1, 4, 5]


何をしているか?

指定した値に、指定した値を入力できる処理を応用している。

a = [1,2,3,4,5]

a[0], a[1], a[2] = a[4], a[4], 5
print(a)

#[5, 5, 5, 4, 5]

シンプル版

変数名をつけていなくても使える。

a,b,c,d =1,2,3,4
a,c = c, a
print(a,b,c,d)

#3 2 1 4

数が合わない場合

左側の値が一つ以外の場合はエラーになる。
左側がひとつの時は、まとまった値が入る。

a = [1,2,3,4,5]

a[0] = a[4], a[4], a[4]
print(a)

#[(5, 5, 5), 2, 3, 4, 5]
a = [1,2,3,4,5]

a[0], a[1] = a[4], a[4], a[4]
print(a)

#ValueError: too many values to unpack (expected 2)
0
0
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
0
0