LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 21.タプル型

Posted at

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

■タプル型

◆タプル型の基本
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> type(t)
<class 'tuple'>

リスト型では[]を使っていたが、
タプル型では()を使う。
タプル型においても、インデックスやスライス、.count().index()などが使える。

◆タプル型とリスト型の違い
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> t[0] = 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

リスト型では後からリスト内の要素を編集できたが、
タプル型では基本的に要素を編集することができない。

◆タプルとタプルの足し算
>>> x = (1, 2, 3)
>>> y = (4, 5, 6)
>>> z = x + y
>>> z
(1, 2, 3, 4, 5, 6)
()の省略
>>> t = 1, 2, 3
>>> t
(1, 2, 3)
>>> type(t)
<class 'tuple'>

()を省略した場合、タプル型と判定される。

>>> a = 1
>>> a
1
>>> type(a)
<class 'int'>

>>> b = 1,
>>> b
(1,)
>>> type(b)
<class 'tuple'>

,がつくと、タプル型と判定される。
うっかりつけてしまった,によりタプル型と判定され、バグの原因になることがあるので注意。

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