まぬねこの足跡。。。

備忘録+たのしさ+ひっそりと

Python タプル(tuple)

概要

  • ()で囲む 省略もOK。
  • 複数のデータを要素としてまとめて取り扱うデータ
  • 構成要素:あらゆる型で混合してよい。
  • 他言語の配列に近い。
  • インデックスで要素を取得のみ。書換不可。

‐ シーケンス型

実行結果

word_tap=(1,2,3,4,5)
word_tap1=11,22,33,44,55
print(word_tap)
print(word_tap1)
print(word_tap[3])
print(word_tap[1:3])
print(type(word_tap))
kara_tap=() # 空のタプル
tap_1=(999,) # データ1つの時
print(kara_tap)
print(tap_1)

表示イメージ

(1, 2, 3, 4, 5)
(11, 22, 33, 44, 55)
4
(2, 3)
<class 'tuple'>
()
(999,)

変換

タプル→リスト 変換

word_tap=(1,2,3,4,5)
print(word_tap)
print(type(word_tap))
word_lis = list(word_tap)
print(word_lis)
print(type(word_lis))
表示イメージ
(1, 2, 3, 4, 5)
<class 'tuple'>
[1, 2, 3, 4, 5]
<class 'list'>

リスト→タプル 変換

word_lis=[1,2,3,4,5]
print(word_lis)
print(type(word_lis))
word_tap = tuple(word_lis)
print(word_tap)
print(type(word_tap))
表示イメージ
[1, 2, 3, 4, 5]
<class 'list'>
(1, 2, 3, 4, 5)
<class 'tuple'>