リスト - 作成、取り出し、置換、追加、検索、削除、要素数

作成

>>> list = ["a", "b", "c", "d", "e"]
>>> list
['a', 'b', 'c', 'd', 'e']

取り出し

>>> list = ["a", "b", "c", "d", "e"]

# n番目の要素を取り出す
>>> list[0]
'a'

# インデクスが負の数だと後ろから数える
>>> list[-1]
'e'

# 範囲外のインデクスを指定するとエラー
>>> list[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

# n番目からm-1番目の要素を取り出す
>>> list[1:4]
['b', 'c', 'd']

# 始点を省略すると0番目から
>>> list[:3]
['a', 'b', 'c']

# 終点を省略すると-1番目まで
>>> list[3:]
['d', 'e']

# 範囲外のインデクスは-1を指定したのと同じ
>>> list[3:10]
['d', 'e']

置換

>>> list = ["a", "b", "c", "d", "e"]

# n番目の要素を置き換える
>>> list[3] = "D"
>>> list
['a', 'b', 'c', 'D', 'e']

# n番目からm-1番目の要素を置き換える
>>> list[:3] = ["A", "B", "C"]
>>> list
['A', 'B', 'C', 'D', e]

# 右辺の要素数が多いと自動的に拡張
>>> list[-1:] = ["E", "F"]
>>> list
['A', 'B', 'C', 'D', 'E', 'F']

# 少ないと縮小
>>> list[-2:] = "E"
>>> list
['A', 'B', 'C', 'D', 'E']

追加

>>> list = ['b']

# 末尾に追加
>>> list.append('e')
>>> list
>>> ['b', 'e']

# n番目の要素の前に追加
>>> list.insert(0, 'a')
>>> list
['a', 'b', 'e']

# n番目の要素の前に複数の要素を追加
>>> list[2:2] = ['c', 'd']
>>> list
['a', 'b', 'c', 'd', 'e']

結合

>>> list1 = ['a', 'b', 'c']
>>> list2 = ['d', 'e']

# 新しいリストを作成して結合
>>> list3 = list1 + list2
>>> list3
['a', 'b', 'c', 'd', 'e']
>>> list1
['a', 'b', 'c']

# 新しいリストを作らずに結合
>>> list1.extend(list2)
>>> list1
['a', 'b', 'c', 'd', 'e']

検索

>>> list = ["a", "b", "c", "a", "b"]

# xがあるかを調べる
>>> "b" in list
True
>>> "e" in list
False

# 最初のxのインデクスを取得
>>> list.index("a")
0

# xが見つからなければエラー
>>> list.index("e")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

削除

>>> list = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']


# 末尾の要素を削除(削除した値を返す)
>>> list.pop()
'b'
>>> list
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']

# n番目の要素を削除
>>> list.pop(0)
'a'
>>> list
['a', 'a', 'b', 'b', 'b', 'c', 'c']

# 1番目のxを削除
>>> list.remove('b')
>>> list
['a', 'a', 'b', 'b', 'c', 'c']

# xが見つからなければエラー
>>> list.remove(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

# 全てのxを削除
>>> while 'b' in list: list.remove('b')
...
>>> list
['a', 'a', 'c', 'c']

# n番目からm-1番目の要素を削除
>>> del list[1:3] # list[1:3] = [] と同じ
>>> list
['a', 'c']

# リストを空にする
>>> del list[:] # list[:] = [] と同じ
>>> list
[]

素数

>>> list = ['a', 'a', 'b', 'c']

# 全体の要素数を数える
>>> len(list)
4

# xの数を数える
>>> list.count('a')
2