3
0

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 1 year has passed since last update.

【Python】「リスト型」「タプル型」「集合型(set)」の違いをまとめてみた

Last updated at Posted at 2023-04-09

はじめに

「リスト型」「タプル型」「集合型」のデータ形式が似ているので、「どれがどんな形式だったっけ?」と迷うことが多いです。
自分の頭を整理するために、それぞれの違いを見比べてみました。

それぞれの基本形を見比べてみる

#リスト型
list_int = [1, 2, 3]
list_str = ['a', 'b', 'c']

#タプル型
tuple = (1, 2, 3)

#集合型(set)
set_int = {1, 2, 3, 1, 2, 3} #集合型は要素を重複させないので、{1, 2, 3} 
set_str = {'a', 'b', 'c','a', 'b', 'c'} #集合型は要素を重複させないので、{'a', 'b', 'c'}  

追加方法を見比べてみる

#リスト型
list_int.append(4) #末尾に'4'を追加
list_str.insert(3, 'd') #4番目に'd'を追加

#タプル型は、追加できません

#集合型(set)
set_int.add(4) #末尾に'4'を追加
set_str.add('d') #末尾に'd'を追加

削除方法を見比べてみる

#リスト型
list_int.pop(4) #'4'を指定して削除
list_str.pop() #末尾の要素を削除
list_str.clear() #全削除

#タプル型は、削除できません

#集合型(set)
set_int.remove(4) #'4'を指定して削除
set_str.discard('d') #存在しない要素を指定してもエラーにならない
set_str.clear() #全削除

まとめ

まずは、シンプルに違いを見比べてみました。
今度は、それぞれの利用シーンなども比べてみたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?