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

【Python入門】リスト/辞書/集合/タプル

Last updated at Posted at 2025-08-12

リストについて

特徴

・角括弧で括る
・カンマ区切りで各要素を設定
・インデックスを指定して要素を取得

list = ["要素1","要素2","要素3","要素4"]
         ^0      ^1       ^2       ^3
         ^-4     ^-3      ^-2      ^-1

x = list[0]  # x の中身は "要素1"
y = list[-2] # y の中身は "要素3" 

・インデックスを指定してリストを分割

list[開始位置:終了位置]
list = ["要素1","要素2","要素3","要素4"]
        ^0      ^1       ^2       ^3    ^4
        ^-4     ^-3      ^-2      ^-1

# 開始位置を省略[:3]
    >>> 最初の位置から3まで
# 終了位置を省略[2:]
    >>> 2から最後の要素まで
# すべて省略[:]
    >>> すべての値を取得

・空のリスト(要素が0個)

x = []
y = list()

・要素の追加

x = [10,20,30]
x.append(40)

・要素の削除

x = [10,20,30]
x.remove(20)

・要素の削除②

# pop([i])は指定された位置の要素をリストから削除し、そのリストを返す

x = [10,20,30]
print(x.pop(1))
>>> 20

・要素の削除③
リスト内の先頭要素を削除する場合、下記のメソッドを使用する

from collections import deque

number = deque([1, 2, 3, 4, 5])
print(number.popleft())
>>> 1

・同じ値の要素を持てる

x = ["a","b","a"]

辞書について

特徴

・keyとvalueを1つのペアとして、そのペアを複数持つことができる
・同じKeyの要素を持つことができない(valueはOK)

辞書 = {key1:value1,key2:value2,key3:value3}
scores = {"国語":82,"数学":70,"英語":74}

・keyを指定してvalueの値を取得

x = 辞書.get(key)

# 上記の例だと...
jpn = scores.get("国語") # 82

・key/value の値だけ取得

辞書.keys()

# 上記の例だと...
x = scores.keys() # ["国語","数学","英語"]

辞書.values()

# 上記の例だと..
y = scores.values() # [82,70,74]

・辞書の要素数を取得

len(辞書)

# 上記の例だと... 
z = len(scores) # 3

・空の辞書

x = {}
y = dict()

集合について

特徴

・複数の値を1つにまとめたもの
・順序がない(インデックスを指定できない)
・同じ値を持てない

x = {1,2,3}

・要素の追加

集合.add(要素)
x = {1,2,3}
x.add(4)

・要素の削除

集合.discard(要素) # 指定した要素が集合になくてもエラーにならない
集合.remove(要素)  # 指定した要素が集合にないとエラーになる

・集合の操作

x = {1,2,4,6}
y = {1,3,5,7}

z = x | y # 和集合
z = x - y # 差集合
z = x & y # 積集合

タプルについて

特徴

・複数の値を1つにまとめたもの
・順序がある
・同じ値を持てる
・値を変更できない(イミュータブル)

x = (1 , 2 , 3)
     ^0  ^1  ^2

y = x[2] # 3
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?