2.

Python リスト要素参照完全ガイド (index/スライス/enumerate/zip)

編集
この記事の要点
  • Python リストは list[0] で先頭、list[-1] で末尾
  • スライス list[start:stop:step] で部分取得。list[::-1] は逆順
  • 存在しないインデックスは IndexError (スライスは空配列が返るので安全)
  • enumerate でインデックスと値を同時取得、zip で複数リストの並列ループ
  • NumPy 配列は 多次元・ブロードキャスト対応で挙動が異なる

インデックス参照の基本

fruits = ['apple', 'banana', 'cherry', 'date']

# 正のインデックス (0 始まり)
fruits[0]     # 'apple'
fruits[1]     # 'banana'
fruits[3]     # 'date'

# 負のインデックス (末尾から)
fruits[-1]    # 'date'
fruits[-2]    # 'cherry'

# 範囲外は IndexError
fruits[10]    # IndexError: list index out of range

# 安全に取りたいなら try / except か len() チェック
if len(fruits) > 10:
    x = fruits[10]

スライス [start:stop:step]

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

nums[2:5]      # [2, 3, 4]      start=2, stop=5 (5 は含まない)
nums[:3]       # [0, 1, 2]      先頭から 3 件
nums[7:]       # [7, 8, 9]      7 から末尾まで
nums[:]        # [0,1,..,9]    全コピー (浅いコピー)

# step
nums[::2]      # [0,2,4,6,8]   2 飛ばし (偶数番目)
nums[1::2]     # [1,3,5,7,9]   1 始まりで 2 飛ばし
nums[::-1]     # [9,8,..,0]    逆順
nums[::-2]     # [9,7,5,3,1]   逆順 2 飛ばし

# スライスは IndexError にならない
nums[100:200]  # [] 空リスト
nums[-100:3]   # [0,1,2]

2 次元リストへのアクセス

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

matrix[0]        # [1, 2, 3] (1 行目)
matrix[0][1]     # 2          (1 行目 2 列目)
matrix[-1][-1]   # 9

# 行を取り出す
row = matrix[1]            # [4, 5, 6]

# 列を取り出す (リスト内包)
col1 = [r[0] for r in matrix]   # [1, 4, 7]

# NumPy なら直接スライス
import numpy as np
a = np.array(matrix)
a[:, 0]    # array([1, 4, 7])  全行の 1 列目
a[1, :]    # array([4, 5, 6])  2 行目全列
a[0:2, 1:3]  # [[2,3],[5,6]] 部分行列

enumerate でインデックスと値を同時取得

fruits = ['apple', 'banana', 'cherry']

# ❌ インデックスを別途管理 (Pythonic でない)
for i in range(len(fruits)):
    print(i, fruits[i])

# ✅ enumerate
for i, fruit in enumerate(fruits):
    print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry

# 開始番号を変えたい
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
# 1 apple
# 2 banana
# 3 cherry

zip で複数リストの並列処理

names = ['Taro', 'Hanako', 'Jiro']
ages  = [30, 25, 40]
roles = ['admin', 'user', 'user']

for name, age, role in zip(names, ages, roles):
    print(f"{name} ({age}) - {role}")

# 辞書化
people = dict(zip(names, ages))
# {'Taro': 30, 'Hanako': 25, 'Jiro': 40}

# Python 3.10+ zip(strict=True) で長さチェック
list(zip(names, ages, strict=True))   # 長さ違うと ValueError

要素の検索: index / count / in

fruits = ['apple', 'banana', 'apple', 'cherry']

# in 演算子 (存在チェック)
'apple' in fruits        # True
'grape' in fruits        # False
'grape' not in fruits    # True

# index() で位置取得 (最初に見つかったもの)
fruits.index('apple')    # 0
fruits.index('grape')    # ValueError

# 安全に
if 'grape' in fruits:
    idx = fruits.index('grape')

# count() で出現回数
fruits.count('apple')    # 2
fruits.count('grape')    # 0

タプル / 文字列との比較

操作listtuplestr
[0] 参照✅ (1文字)
スライス
要素変更 ([0] = x)✅ 変更可❌ TypeError
append / pop
ハッシュ化 (dict キー)

スライス代入と削除

nums = [0, 1, 2, 3, 4, 5]

# 範囲をまとめて置換 (個数違っても OK)
nums[1:3] = [10, 20, 30]   # [0, 10, 20, 30, 3, 4, 5]

# 範囲削除
del nums[1:4]              # [0, 3, 4, 5]

# 全削除
nums[:] = []

# 末尾 1 件削除 ≒ pop()
nums = [1, 2, 3]
del nums[-1]               # [1, 2]
nums.pop()                 # 同じ

FAQ

Q: list[-1]list[len(list)-1] の違い
A: 結果は同じですが、-1 が Pythonic で短いです。

Q: スライスはコピー?参照?
A: 浅いコピーを作ります。a[:] でリストの複製は OK ですが、内部要素 (ネストされた list / dict) は参照共有。深いコピーは copy.deepcopy()

Q: 範囲外スライスがエラーにならない理由
A: 設計思想として「失敗より空を返す」。nums[100:200] は空リスト [] を返します。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. リストの作成
  2. 要素の参照
  3. 要素の追加
  4. 要素の更新
  5. 要素の削除
  6. 要素の数を確認