リストとは
リスト(list)は、複数の値を順番に格納できるデータ構造です。角括弧 [] で作ります。
python
nums = [1, 2, 3, 4, 5]fruits = ["apple", "banana", "cherry"]mixed = [1, "hello", 3.14, True] # 異なる型も混在できるempty = [] # 空のリストlen() でリストの要素数を取得できます。
python
len([1, 2, 3]) # 3len([]) # 0リストとインデックス
リストの各要素にはインデックスでアクセスできます(文字列と同様)。
python
fruits = ["apple", "banana", "cherry"]# 0 1 2# -3 -2 -1fruits[0] # "apple"fruits[1] # "banana"fruits[-1] # "cherry"(末尾)リストの要素の変更
文字列と違い、リストの要素は変更できます(ミュータブル)。
python
fruits = ["apple", "banana", "cherry"]fruits[1] = "mango"fruits # ["apple", "mango", "cherry"]リストのスライス
python
nums = [0, 1, 2, 3, 4, 5]nums[1:4] # [1, 2, 3]nums[:3] # [0, 1, 2]nums[3:] # [3, 4, 5]nums[::2] # [0, 2, 4]nums[::-1] # [5, 4, 3, 2, 1, 0](逆順)リストに対する関数・演算子・メソッド
組み込み関数
python
nums = [3, 1, 4, 1, 5, 9, 2, 6]len(nums) # 8sum(nums) # 31max(nums) # 9min(nums) # 1sorted(nums) # [1, 1, 2, 3, 4, 5, 6, 9](元のリストは変化しない)演算子
python
[1, 2] + [3, 4] # [1, 2, 3, 4](結合)[0] * 5 # [0, 0, 0, 0, 0](繰り返し)3 in [1, 2, 3] # True(含まれるか)4 in [1, 2, 3] # Falseリストのメソッド
python
nums = [1, 2, 3]# 追加nums.append(4) # [1, 2, 3, 4](末尾に追加)nums.insert(1, 10) # [1, 10, 2, 3, 4](位置1に追加)nums.extend([5, 6]) # [1, 10, 2, 3, 4, 5, 6](別リストを結合)# 削除nums.pop() # 6(末尾を取り出して削除)nums.pop(0) # 1(インデックス0を取り出して削除)nums.remove(10) # 最初に見つかった10を削除# 検索・ソートnums = [3, 1, 4, 1, 5]nums.index(4) # 2(4の位置)nums.count(1) # 2(1の個数)nums.sort() # [1, 1, 3, 4, 5](昇順ソート、元を変更)nums.reverse() # [5, 4, 3, 1, 1](逆順、元を変更)注意:
sort()とsorted()の違い:
list.sort(): リスト自体を変更する(破壊的操作)。返値はNonesorted(list): 新しいリストを返す(元のリストは変化しない)
タプル (tuple)
タプル(tuple)は、リストに似ていますが変更できない(イミュータブル)データ構造です。丸括弧 () で作ります。
python
t = (1, 2, 3)t[0] # 1t[-1] # 3# 1要素のタプルはカンマが必要t1 = (1,) # タプルt2 = (1) # ただの整数!# タプルは変更できないt[0] = 10 # TypeError!タプルのアンパック
python
point = (3, 4)x, y = point # アンパックx # 3y # 4# 複数の変数を同時に代入a, b = 1, 2a, b = b, a # 変数の値を交換for文による繰り返しとリスト・タプル
for 文を使うと、リストやタプルの要素を順に処理できます。
python
fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit)# apple# banana# cherryインデックスと要素の両方を使う
python
fruits = ["apple", "banana", "cherry"]for i, fruit in enumerate(fruits): print(f"{i}: {fruit}")# 0: apple# 1: banana# 2: cherry練習: リストの合計
リストの全要素の合計を返す関数 my_sum(lst) を、組み込みの sum() を使わずに定義してください。
練習: flatten
2次元リスト(リストのリスト)を1次元のリストに変換する関数 flatten(lst) を定義してください。