Pythonリストの基本操作と使い方

要素の検索と確認

index(x) は、リスト内で最初に見つかった値 x のインデックスを返します。

items = ['apple', 'banana', 'cherry']
print(items.index('banana'))  # 出力: 1

count(x) は、リスト内に含まれる値 x の出現回数を返します。

values = [1, 2, 2, 3, 2, 4]
print(values.count(2))  # 出力: 3

in 演算子は、指定した要素がリストに存在するかどうかを真偽値で返します。

items = ['apple', 'banana', 'cherry']
print('banana' in items)  # 出力: True

リストの変更

append(x) は、リストの末尾に要素 x を追加します。

items = ['apple', 'banana', 'cherry']
items.append('orange')
print(items)  # 出力: ['apple', 'banana', 'cherry', 'orange']

extend(iterable) は、イテラブルなオブジェクトの各要素をリストの末尾に追加します。

items = ['apple', 'banana', 'cherry']
items.extend(['orange', 'grape'])
print(items)  # 出力: ['apple', 'banana', 'cherry', 'orange', 'grape']

insert(i, x) は、インデックス i の位置に要素 x を挿入します。

items = ['apple', 'banana', 'cherry']
items.insert(1, 'orange')
print(items)  # 出力: ['apple', 'orange', 'banana', 'cherry']

remove(x) は、リスト内で最初に見つかった値 x を削除します。

items = ['apple', 'banana', 'cherry']
items.remove('banana')
print(items)  # 出力: ['apple', 'cherry']

pop(i) は、指定したインデックス i の要素を削除し、その値を返します。引数を省略すると末尾の要素が対象になります。

items = ['apple', 'banana', 'cherry']
removed = items.pop(1)
print(removed)  # 出力: 'banana'
print(items)    # 出力: ['apple', 'cherry']

clear() は、リスト内のすべての要素を削除します。

items = ['apple', 'banana', 'cherry']
items.clear()
print(items)  # 出力: []

reverse() は、リストの要素順序を逆転させます。

items = ['apple', 'banana', 'cherry']
items.reverse()
print(items)  # 出力: ['cherry', 'banana', 'apple']

sort(key=None, reverse=False) は、リストをインプレースでソートします。必要に応じて比較キーと降順フラグを指定できます。

nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]
nums.sort()
print(nums)  # 出力: [1, 1, 2, 3, 4, 5, 5, 6, 9]

その他の便利な操作

copy() は、リストの浅いコピーを生成します。

original = ['apple', 'banana', 'cherry']
duplicate = original.copy()
print(duplicate)  # 出力: ['apple', 'banana', 'cherry']

len(list) は、リストの要素数を返します。

items = ['apple', 'banana', 'cherry']
print(len(items))  # 出力: 3

スライス記法 list[start:end] を使うと、リストの一部を新しいリストとして取り出せます。

data = [1, 2, 3, 4, 5]
subset = data[1:4]
print(subset)  # 出力: [2, 3, 4]

リストの結合と演算

+ 演算子により、2つのリストを連結して新しいリストを作成できます。

a = [1, 2, 3]
b = [4, 5, 6]
merged = a + b
print(merged)  # 出力: [1, 2, 3, 4, 5, 6]

タグ: Python List データ構造

6月16日 23:53 投稿