変更できる順序付きのコレクション
リストは、角かっこの中に値を順番どおりに保持します。[184.0, 185.5, 183.2] のように書き、どんな値でも入れられ、len(prices) で個数がわかります。各要素には インデックス という位置があり、0 から数えます。負のインデックスは末尾から数えるので、-1 が最後の要素です。存在しない位置を指定すると IndexError になります。
prices = [184.0, 185.5, 183.2, 186.1]
# Reading by position
print(prices[0]) # 184.0
print(prices[-1]) # 186.1
print(len(prices)) # 4
# A list is changeable: assign to a position
prices[1] = 185.0
print(prices) # [184.0, 185.0, 183.2, 186.1]スライス:リストの一部を取り出す
prices[start:stop] は start から stop の手前までの新しいリストを返します。片方を省略するとその端まで続き、prices[:3] は先頭3つ、prices[-3:] は末尾3つです。範囲を超えてもエラーにならず、末尾で止まるだけです。落とし穴が1つあり、-0 は 0 と同じなので、prices[-0:] は空ではなくリスト全体になります。
prices = [184.0, 185.0, 183.2, 186.1, 187.4]
# Slices are new lists
print(prices[1:3]) # [185.0, 183.2]
print(prices[:2]) # [184.0, 185.0]
print(prices[-2:]) # [186.1, 187.4]
# Going past the end is fine, but -0 is not "none"
print(prices[3:99]) # [186.1, 187.4]
print(prices[-0:]) # the whole list追加と削除
append(x) は末尾に1つ追加し、extend(items) は複数を追加し、insert(i, x) は位置 i に入れます。pop() は最後の要素を取り除いて返し(pop(i) は位置 i のもの)、remove(x) は x に等しい最初の要素を削除します。これらのメソッドはリストをその場で変更して None を返すので、prices = prices.append(1) とすると prices は None になります。+ で足すと新しいリストができます。
# Changing a list in place
fills = [100, 250]
fills.append(75)
fills.extend([40, 60])
print(fills) # [100, 250, 75, 40, 60]
last = fills.pop()
fills.remove(250)
print(last, fills) # 60 [100, 75, 40]
# + builds a new list and leaves the old ones alone
both = fills + [10]
print(both, fills) # [100, 75, 40, 10] [100, 75, 40]並べ替え
並べ替えには2通りあります。prices.sort() はリストをその場で並べ替えて None を返します。sorted(prices) は元のリストをそのままにして、並べ替えた新しいリストを返し、任意のイテラブルも受け取れます。どちらも、大きい順にする reverse=True と、別の基準で並べる key=...(例:key=len)を使えます。元の順序を他のコードが使うかもしれないときは sorted を選びましょう。
# sorted() returns a new list, sort() changes the old one
prices = [185.0, 183.2, 187.4, 184.0]
ranked = sorted(prices, reverse=True)
print(ranked) # [187.4, 185.0, 184.0, 183.2]
print(prices) # [185.0, 183.2, 187.4, 184.0] (unchanged)
prices.sort()
print(prices) # [183.2, 184.0, 185.0, 187.4]名前は2つ、リストは1つ
backup = prices はリストをコピーしません。2つの名前が同じオブジェクトを指すので、片方を変えるともう片方も変わります。本当の(浅い)コピーは prices.copy()、list(prices)、スライス prices[:] で作ります。関数でも同じで、引数に .append、.sort、.pop を使う関数は呼び出し側のリストも変えてしまいますが、呼び出し側はそれを期待していないことがほとんどです。
# A second name is not a copy
prices = [184.0, 185.0]
alias = prices
alias.append(186.0)
print(prices) # [184.0, 185.0, 186.0]
# A real copy is independent
backup = list(prices)
backup.append(187.0)
print(prices) # [184.0, 185.0, 186.0]
print(backup) # [184.0, 185.0, 186.0, 187.0]sorted(...)、スライス、内包表記を使いましょう。ラボでは、渡したリストが後で変わっていないことも確認します。items[i]、items[-1]:1つの要素。items[a:b]:新しいリストappend、extend、insert、pop、remove:リストを変更し、役に立つ値は返さないsorted(items):並べ替えた新しいリストを作る。items.sort():その場で並べ替える
次はタプルとアンパックです。サイズが固定のリストの仲間で、値をきれいに取り出す方法を学びます。
ラボ:採点される内容
top_nで高い価格を上位から選ぶ25点last_nで最新の値を取り出す25点moving_averageで価格のウィンドウごとの平均を求める25点rotateで値を端から端へ回す25点