Pythonリストとタプルの実践的な使い方

リストの基礎

Pythonのリストは [] で囲み、カンマ区切りで要素を格納する可変長シーケンスです。異なる型を混在させることも可能です。

games = ['Apex Legends', 'Valorant', 'Elden Ring', 'CS2', 'Fortnite']

# インデックスアクセス
first = games[0]          # 'Apex Legends'
nested = games[0][2]      # 'e'
last = games[-1]          # 'Fortnite'
slice_ex = games[1:4]     # ['Valorant', 'Elden Ring', 'CS2']

要素の追加・挿入・拡張

末尾追加 append()

weapons = ['AK-47', 'M4A1']
weapons.append('AWP')
print(weapons)  # ['AK-47', 'M4A1', 'AWP']

任意位置挿入 insert()

ranks = ['Iron', 'Gold', 'Diamond']
ranks.insert(1, 'Bronze')   # インデックス1に挿入
ranks.insert(99, 'Radiant') # 範囲外でも最後尾に追加
print(ranks)

イテラブル展開 extend()

teams = ['Fnatic', 'G2']
teams.extend('TL')          # 文字列を1文字ずつ追加
print(teams)  # ['Fnatic', 'G2', 'T', 'L']

削除メソッド群

pop() – 位置指定削除&返却

players = ['s1mple', 'ZywOo', 'sh1ro']
removed = players.pop()     # 末尾削除
print(removed, players)     # sh1ro ['s1mple', 'ZywOo']

remove() – 値指定削除

maps = ['Dust2', 'Mirage', 'Inferno']
maps.remove('Mirage')
print(maps)  # ['Dust2', 'Inferno']

clear() – 全削除

temp = [1, 2, 3]
temp.clear()
print(temp)  # []

del ステートメント – スライス削除

scores = [100, 200, 300, 400]
del scores[1:3]
print(scores)  # [100, 400]

要素の更新

単一インデックス更新

heroes = ['Jett', 'Sage', 'Omen']
heroes[2] = 'Cypher'
print(heroes)

スライス一括更新

agents = ['Phoenix', 'Reyna', 'Breach', 'Killjoy']
agents[1:3] = ['Raze', 'Viper', 'Skye']  # 要素数が異なってもOK
print(agents)

agents[::2] = ['Yoru', 'Astra']  # ステップ指定時は長さ一致必須

反復と集計

chars = ['A', 'B', 'C', 'A']
print(chars.count('A'))  # 2
print(len(chars))        # 4

# ソート
nums = [5, 1, 9, 3]
nums.sort()
print(nums)          # [1, 3, 5, 9]

nums.sort(reverse=True)
print(nums)          # [9, 5, 3, 1]

# 反転
nums.reverse()
print(nums)          # [1, 3, 5, 9]

ネストしたリストの操作

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

print(matrix[1][2])  # 6

タプル – 不変シーケンス

タプルは () で囲み、要素の追加・削除・変更ができません。単一要素の場合は末尾にカンマが必須です。

single = (42,)      # タプル
not_tuple = (42)    # int

colors = ('red', 'green', 'blue')
# colors[0] = 'yellow'  # TypeError

# タプル内の可変オブジェクトは変更可能
config = ([1, 2], [3, 4])
config[0].append(99)
print(config)  # ([1, 2, 99], [3, 4])

rangeによる数値ジェネレータ

for level in range(1, 6, 2):
    print(f'Level {level}')
# Level 1
# Level 3
# Level 5

タグ: Python リスト タプル range append

7月4日 22:13 投稿