LoginSignup
1
0

More than 1 year has passed since last update.

Python タプル

Posted at

はじめに

基礎から定着させていこうということでタプルについてまとめました。
Python 3.8.2

タプルの作成

tuple.py
t = (1,2,3,4,5)

print("t is",type(t))
print(t)
出力結果
t is <class 'tuple'>
(1, 2, 3, 4, 5)

要素が一つでもタプルは作成できるが、「,」を忘れずに

tuple.py
t1 = (1,)
t2 = 1,

print("t1 is",type(t1))
print(t1)
print("t2 is",type(t2))
print(t2)
出力結果
t1 is <class 'tuple'>
(1,)
t2 is <class 'tuple'>
(1,)

タプルの要素の追加

tuple.py
t = (1,2,3,4,5)
print(t[0])
t[0] = 10

タプルに要素を追加しようとするとエラーが発生する

出力結果
1
Traceback (most recent call last):
  File "tuple.py", line 15, in <module>
    t[0] = 10
TypeError: 'tuple' object does not support item assignment

タプルのスライス

tuple.py
print(t[1:4])
出力結果
(2, 3, 4)

タプルの結合

tuple.py
t = (1,2,3) + (4,5,6)
print(t)

要素を追加したければ新しいタプルを作成する

出力結果
(1, 2, 3, 4, 5, 6)

タプルのアンパック

tuple.py
t = (1,2,3)

x,y,z = t
print(x,y,z)
print("x is",type(x))
出力結果
1 2 3
x is <class 'int'>

タプルを使った入れ替え

tuple.py
a = 1
b = 2
a,b = b,a
print(a,b)
出力結果
2 1

詳しく見てみる

tuple.py
a = 1
b = 2

print("a is",type(a))
print("b is",type(b))
#b,aとすることでタプルにしている
n = b,a
print("n is",type(n))
a,b = n
print(a,b)
出力結果
a is <class 'int'>
b is <class 'int'>
n is <class 'tuple'>
2 1

以上

1
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
1
0