作成
>>> list = ["a", "b", "c", "d", "e"]
>>> list
['a', 'b', 'c', 'd', 'e']
取り出し
>>> list = ["a", "b", "c", "d", "e"]
>>> 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
>>> list[1:4]
['b', 'c', 'd']
>>> list[:3]
['a', 'b', 'c']
>>> list[3:]
['d', 'e']
>>> list[3:10]
['d', 'e']
置換
>>> list = ["a", "b", "c", "d", "e"]
>>> list[3] = "D"
>>> list
['a', 'b', 'c', 'D', 'e']
>>> 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']
>>> list.insert(0, 'a')
>>> list
['a', 'b', 'e']
>>> 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"]
>>> "b" in list
True
>>> "e" in list
False
>>> list.index("a")
0
>>> 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']
>>> list.pop(0)
'a'
>>> list
['a', 'a', 'b', 'b', 'b', 'c', 'c']
>>> list.remove('b')
>>> list
['a', 'a', 'b', 'b', 'c', 'c']
>>> list.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> while 'b' in list: list.remove('b')
...
>>> list
['a', 'a', 'c', 'c']
>>> del list[1:3]
>>> list
['a', 'c']
>>> del list[:]
>>> list
[]
>>> list = ['a', 'a', 'b', 'c']
>>> len(list)
4
>>> list.count('a')
2