LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 22. タプルのアンパッキング

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■タプルのアンパッキング

◆タプルをバラす
tuple_unpacking
num_tuple = (10, 20)
print(num_tuple)

x, y = num_tuple
print('x =', x, type(x))
print('y =', y, type(y))
result
(10, 20)
x = 10 <class 'int'>
y = 20 <class 'int'>

タプルの要素をバラすことができる。

◆並列で代入することの実際
tuple
X, Y = (0, 100)
print('X = ', X, type(X))
print('Y = ', Y, type(Y))

min, max = 0, 100
print('min = ', min, type(min))
print('max = ', max, type(max))
result
X =  0 <class 'int'>
Y =  100 <class 'int'>
min =  0 <class 'int'>
max =  100 <class 'int'>

タプルは()を省略することができた。
minmaxのように並列で記載するということは、
一旦0, 100がタプルと判定されたあと、それがアンパッキングされた結果、
int型となって代入されたことになる。

◆タプルのアンパッキングを利用したオブジェクトの入れ替え
change_object
a, b = 1, 2
print(a, b)

a, b = b, a
print(a, b)
result
1 2
2 1

一度代入したオブジェクトを入れ替えることができる。

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