spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0]) # 'cat' print(spam[1]) # 'bat' print(spam[2]) # 'rat' print(spam[3]) # 'elephant' print(['cat', 'bat', 'rat', 'elephant'][3]) # 'elephant' print('Hello ' + spam[0]) # 'Hello cat' print('The ' + spam[1] + 'ate the ' + spam[0] + '.') # 'The bat ate the cat.'
spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[1000])
実行結果
IndexError: list index out of range
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] print(spam[0]) # ['cat', 'bat'] print(spam[0][1]) # 'bat' print(spam[1][4]) # '50'
# 負のインデックス spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[-1]) # 'elephant' print(spam[-3]) # 'bat' print('The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.') # 'The elephant is afraid of the bat.'
# スライスを用いて部分リストを取得する spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0:4]) # ['cat', 'bat', 'rat', 'elephant'] print(spam[1:3]) # ['bat', 'rat'] print(spam[0:-1]) # ['cat', 'bat', 'rat'] print(spam[:2]) # ['bat', 'rat'] print(spam[1:]) # ['bat', 'rat', 'elephant'] print(spam[:]) # ['cat', 'bat', 'rat', 'elephant']
# len()関数を用いてリストの長さを取得する spam = ['cat', 'bat', 'rat', 'elephant'] len(spam)
出力結果
3
# インデックスを用いてリストの中の値を変更する spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aaardvark' print(spam) # spam = ['cat', 'aaardvark', 'rat', 'elephant'] spam[2] = spam[1] print(spam) # spam = ['cat', 'aaardvark', 'aaardvark', 'elephant'] spam[-1] = 12345 print(spam) # spam = ['cat', 'aaardvark', 'aaardvark', 12345]
# リストの連結とリストの複製 spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] print(spam)
# del文を用いてリストから値を削除する spam = ['cat', 'bat', 'rat', 'elephant'] del spam[2] print(spam) # ['cat', 'bat', 'elephant'] del spam[2] print(spam) # ['cat', 'bat']
cat_names = [] while True: print('猫' + str(len(cat_names) + 1) + 'の名前を入力してください' + '(終了するにはEnterキだけ押してください)') name = input() if name == '': break cat_names = cat_names + [name] # リストの連結 print('猫の名前は次のとおり:') for name in cat_names: print(' ' + name)
# inとnot in演算子 print('howdy' in ['hello', 'hi', 'howdy', 'heyas']) # True spam = ['hello', 'hi', 'howdy', 'heyas'] print('cat' in spam) # False print('howdy' not in spam) # False print('cat' not in spam) # True
# 複数代入法 cat = ['fat', 'black', 'loud'] size = cat[0] color = cat[1] disposition = cat[2] # 代わりに、以下のように書くことができる cat = ['fat', 'black', 'loud'] size, color, disposition = cat
# 累積代入演算子 spam = 42 spam = spam + 1 print(spam) # 代わりに、以下のように書くことができる spam = 42 spam += 1 print(spam)
43 43
spam = 'Hello' spam += ' world!' print(spam) # 'Hello world!' bacon = ['Zophie'] bacon *= 3 print(bacon) # ['Zophie', 'Zophie', 'Zophie']
# index()メソッドと=を用いてリストから値を検索する spam = ['hello', 'hi', 'howdy', 'heyas'] print(spam.index('hello')) # 0 print(spam.index('heyas')) # 3 print(spam.index('howdy howdy howdy')) # ValueError: 'hello' is not in list spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] print(spam.index('Pooka')) # 1
# append()メソッドとinsert()メソッドを用いてリストに値を追加する spam = ['cat', 'dog', 'bat'] spam.append('moose') print(spam) # ['cat', 'dog', 'bat', 'moose'] # insert()メソッドはリストの任意の場所に挿入することができる spam.insert(1, 'chicken') print(spam) # ['cat', 'chicken', 'dog', 'bat', 'moose'] # append()もinsert()も戻り値として新しいspamの値を返さない # append()もinsert()も文字列や定数など他の値に対して呼び出すことができない eggs = 'hello' eggs.append('world') # AttributeError: 'str' object has no attribute 'append' bacon = 42 bacon.insert(1, 'world') # AttributeError: 'int' object has no attribute 'insert'
# remove()メソッドを用いてリストから値を削除する spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('bat') print(spam) # ['cat', 'rat', 'elephant'] # リストに含まれない値を削除しようとすると、ValueError例外になる spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('chicken') # ValueError: list.remove(x): x not in list # リストに値が複数含まれる場合、最初の値だけが削除される spam = ['cat', 'bat', 'rat', 'elephant', 'hat', 'cat'] spam.remove('cat') print(spam) # ['bat', 'rat', 'elephant', 'hat', 'cat']
spam = [2, 5, 3.14, 1, -7] spam.sort() print(spam) # [-7, 1, 2, 3.14, 5] spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] spam.sort() print(spam) # ['ants', 'badgers', 'cats', 'dogs', 'elephants'] # 逆順にソート spam.sort(reverse=True) print(spam) # ['elephants', 'dogs', 'cats', 'badgers', 'ants'] # 数と文字列の両方が混ざったリストはソートできない spam = [1, 3, 2, 4, 'Alice', 'Bob'] spam.sort() # TypeError: '<' not supported between instances of 'str' and 'int' # 大文字は小文字より前に来る spam = ['Alice', 'ants', 'Bob', 'badgers' ,'Carol', 'cats'] spam.sort() print(spam) # ['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats'] # 通常のアルファベット順にソートしたい時には、keyというキーワードを引数にstr.lowerを渡してsort()メソッドを呼び出す spam = ['a', 'z', 'A', 'Z'] spam.sort(key=str.lower) print(spam) # ['a', 'A', 'z', 'Z']
# リストを用いたマジック8ボール import random messages = [ '確かにそうだ', '間違いなくそうだ', 'はい', 'なんとも。もういちどやってみて', 'あとでもう一度きいてみて', '集中してもう一度きいてみて', '私の答えはノーです', '見通しはそれほどよくない', 'とても疑わしい' ] print(messages[random.randint(0, len(messages) - 1)])
# リスト:ミュータブル(変更可能) # 文字列:イミュータブル(変更不可) name = 'Zophie a cat' name[7] = 'the' # TypeError: 'str' object does not support item assignment
name = 'Zophie a cat' new_name = name[0:7] + 'the' + name[8:12] print(name) # Zophie a cat print(new_name) # Zophie the cat
# タプル型 eggs = ('hello', 42, 0.5) print(eggs[0]) # hello print(eggs[1:3]) # (42, 0.5) print(len(eggs)) # 3
# タプルは文字列と同様にイミュータブル。タプルは値を変更したり追加したり削除したりすることができない eggs = ('hello', 42, 0.5) eggs[1] = 99 # TypeError: 'tuple' object does not support item assignment
# list()関数とtuple()関数を使って型を変換する print(tuple(['cat', 'dog', 5])) # ('cat', 'dog', 5) print(list(['cat', 'dog', 5])) # ['cat', 'dog', 5] print(list('hello')) # ['h', 'e', 'l', 'l', 'o']
# リストは以上のようにはならない。リストを変数に代入すると、実際にはリストの参照を変数に代入している。 spam = [0, 1, 2, 3, 4, 5] # spamにはリストの参照が代入されている cheese = spam # リストの参照のみがコピーされ、リストの値そのものはコピーされない cheese[1] = 'Hello!' # cheeseの最初の要素を変更すると、spamが参照しているのと同じリストを変更することになる。 print(spam) # [0, 'Hello!', 2, 3, 4, 5] print(cheese) # [0, 'Hello!', 2, 3, 4, 5] # cheeseが参照しているリストを変更すると、spamが参照するリストも変わる。なぜなら、cheeseとspamは同じリストを参照しているから。
# 参照を渡す def eggs(some_parameter): some_parameter.append('Hello') spam = [1, 2, 3] eggs(spam) print(spam) # [1, 2, 3, 'Hello'] # spamとsome_parameterはどちらも同じリストを参照している。そのため、関数から戻った後でも、関数の中でのappend('Hello')がリストに影響を及ぼしている。
# copyモジュールのcopy()関数とdecopy()関数 import copy spam = ['A', 'B', 'C', 'D'] cheese = copy.copy(spam) cheese[1] = 42 print(spam) # ['A', 'B', 'C', 'D'] print(cheese) # ['A', 42, 'C', 'D'] # spamとcheeseは異なるリストを参照するようになった。そのため、cheeseのインデックス1に42を代入すると、cheeseだけが変更されspamには影響がない。