3
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 5 years have passed since last update.

基礎知識の補填 Python (タプル)

Posted at

今回は、タプルについてリストとの違いが曖昧だったので勉強し直してみた。

##タプルとは

  • タプルは、リストとよく似ているデータ型である。

  • 基本的にリストと同じようにインデックスを使って要素を管理することができる。
    また、インデックス指定で要素を取り出したり、スライスを使用して複数要素を取り出すことができる。

タプルがリストと異なるところ

  • タプルはリストと違って要素を書き換えることができない。

  • インデックス指定した要素へ代入して要素を書き換えるということができない。
    一度、作ったタプルは、要素を追加したり削除したりして長さを変更することができないようになっている。

タプルの定義

タプルは、丸括弧()で要素を囲み、要素同士はカンマ(,)で区切る。

タプル = (要素1, 要素2, ・・・)

使用例

>>> t = (1, 2, 3, 4)
>>> t
(1, 2, 3, 4)  # 出力結果

スライス使用例

>>> t[0]
1

>>> t[1:3]
(2, 3)

書き換えることができない

>>> t[0] = 'five'  # ←文字列で更新しようとすると怒られる
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

足し算(連結)することが可能

要素の書き換えや削除等はできないが、新たな要素と足し合わせて(連結)別な変数に入れ込むことが可能。

>>> t2 = t + (10, 20, 30)                                                                                            
>>> t2
(1, 2, 3, 4, 10, 20, 30)

タプルを使用するときの注意点

値が1つしかないタプルを作りたい場合は注意が必要。
値が1つしか入ってなくなくても、カンマを付けとかないとタプルとして認識されない。

t3 = (1, )
3
2
2

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
3
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?