データ構造
**********

この章では、すでに学んだことについてより詳しく説明するとともに、いくつ
か新しいことを追加します。


リスト型についてもう少し
========================

リストデータ型には、他にもいくつかメソッドがあります。リストオブジェク
トのすべてのメソッドを以下に示します:

list.append(x)

   Add an item to the end of the list; equivalent to "a[len(a):] =
   [x]".

list.extend(L)

   Extend the list by appending all the items in the given list;
   equivalent to "a[len(a):] = L".

list.insert(i, x)

   指定した位置に要素を挿入します。第 1 引数は、リストのインデクスで、
   そのインデクスを持つ要素の直前に挿入が行われます。従って、
   "a.insert(0, x)" はリストの先頭に挿入を行います。また
   "a.insert(len(a), x)" は "a.append(x)" と等価です。

list.remove(x)

   Remove the first item from the list whose value is *x*. It is an
   error if there is no such item.

list.pop([i])

   リスト中の指定された位置にある要素をリストから削除して、その要素を
   返します。インデクスが指定されなければ、 "a.pop()" はリストの末尾の
   要素を削除して返します。この場合も要素は削除されます。 (メソッドの
   用法 (signature) で *i* の両側にある角括弧は、この引数がオプション
   であることを表しているだけなので、角括弧を入力する必要はありません
   。この表記法は Python Library Reference の中で頻繁に見ることになる
   でしょう。)

list.index(x)

   Return the index in the list of the first item whose value is *x*.
   It is an error if there is no such item.

list.count(x)

   リストでの *x* の出現回数を返します。

list.sort(cmp=None, key=None, reverse=False)

   リストの項目を、インプレース演算 (in place、元のデータを演算結果で
   置き換えるやりかた) でソートします。引数はソート方法のカスタマイズ
   に使えます。 "sorted()" の説明を参照してください。

list.reverse()

   Reverse the elements of the list, in place.

以下にリストのメソッドをほぼ全て使った例を示します:

   >>> a = [66.25, 333, 333, 1, 1234.5]
   >>> print a.count(333), a.count(66.25), a.count('x')
   2 1 0
   >>> a.insert(2, -1)
   >>> a.append(333)
   >>> a
   [66.25, 333, -1, 333, 1, 1234.5, 333]
   >>> a.index(333)
   1
   >>> a.remove(333)
   >>> a
   [66.25, -1, 333, 1, 1234.5, 333]
   >>> a.reverse()
   >>> a
   [333, 1234.5, 1, 333, -1, 66.25]
   >>> a.sort()
   >>> a
   [-1, 1, 66.25, 333, 333, 1234.5]
   >>> a.pop()
   1234.5
   >>> a
   [-1, 1, 66.25, 333, 333]

You might have noticed that methods like "insert", "remove" or "sort"
that only modify the list have no return value printed – they return
the default "None".  This is a design principle for all mutable data
structures in Python.


リストをスタックとして使う
--------------------------

リスト型のメソッドのおかげで、簡単にリストをスタックとして使えます。ス
タックでは、最後に追加された要素が最初に取り出されます (「last-in,
first-out」)。スタックの一番上に要素を追加するには "append()" を使いま
す。スタックの一番上から要素を取り出すには "pop()" をインデクスを指定
せずに使います。例えば以下のようにします:

   >>> stack = [3, 4, 5]
   >>> stack.append(6)
   >>> stack.append(7)
   >>> stack
   [3, 4, 5, 6, 7]
   >>> stack.pop()
   7
   >>> stack
   [3, 4, 5, 6]
   >>> stack.pop()
   6
   >>> stack.pop()
   5
   >>> stack
   [3, 4]


リストをキューとして使う
------------------------

リストをキュー (queue) として使うことも可能です。この場合、最初に追加
した要素を最初に取り出します (「first-in, first-out」)。しかし、リスト
では効率的にこの目的を達成することが出来ません。追加（append）や取り出
し（pop）をリストの末尾に対して行うと速いのですが、挿入（insert）や取
り出し（pop）をリストの先頭に対して行うと遅くなってしまいます（他の要
素をひとつずつずらす必要があるからです）。

キューの実装には、 "collections.deque" を使うと良いでしょう。このクラ
スは良く設計されていて、高速な追加（append）と取り出し（pop）を両端に
対して実現しています。例えば以下のようにします:

   >>> from collections import deque
   >>> queue = deque(["Eric", "John", "Michael"])
   >>> queue.append("Terry")           # Terry arrives
   >>> queue.append("Graham")          # Graham arrives
   >>> queue.popleft()                 # The first to arrive now leaves
   'Eric'
   >>> queue.popleft()                 # The second to arrive now leaves
   'John'
   >>> queue                           # Remaining queue in order of arrival
   deque(['Michael', 'Terry', 'Graham'])


Functional Programming Tools
----------------------------

There are three built-in functions that are very useful when used with
lists: "filter()", "map()", and "reduce()".

"filter(function, sequence)" returns a sequence consisting of those
items from the sequence for which "function(item)" is true. If
*sequence* is a "str", "unicode" or "tuple", the result will be of the
same type; otherwise, it is always a "list".  For example, to compute
a sequence of numbers divisible by 3 or 5:

   >>> def f(x): return x % 3 == 0 or x % 5 == 0
   ...
   >>> filter(f, range(2, 25))
   [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

"map(function, sequence)" calls "function(item)" for each of the
sequence’s items and returns a list of the return values.  For
example, to compute some cubes:

   >>> def cube(x): return x*x*x
   ...
   >>> map(cube, range(1, 11))
   [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or "None" if some sequence is
shorter than another).  For example:

   >>> seq = range(8)
   >>> def add(x, y): return x+y
   ...
   >>> map(add, seq, seq)
   [0, 2, 4, 6, 8, 10, 12, 14]

"reduce(function, sequence)" returns a single value constructed by
calling the binary function *function* on the first two items of the
sequence, then on the result and the next item, and so on.  For
example, to compute the sum of the numbers 1 through 10:

   >>> def add(x,y): return x+y
   ...
   >>> reduce(add, range(1, 11))
   55

If there’s only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.

A third argument can be passed to indicate the starting value.  In
this case the starting value is returned for an empty sequence, and
the function is first applied to the starting value and the first
sequence item, then to the result and the next item, and so on.  For
example,

   >>> def sum(seq):
   ...     def add(x,y): return x+y
   ...     return reduce(add, seq, 0)
   ...
   >>> sum(range(1, 11))
   55
   >>> sum([])
   0

Don’t use this example’s definition of "sum()": since summing numbers
is such a common need, a built-in function "sum(sequence)" is already
provided, and works exactly like this.


リストの内包表記
----------------

リスト内包表記はリストを生成する簡潔な手段を提供しています。主な利用場
面は、あるシーケンスや iterable (イテレート可能オブジェクト) のそれぞ
れの要素に対してある操作を行った結果を要素にしたリストを作ったり、ある
条件を満たす要素だけからなる部分シーケンスを作成することです。

例えば、次のような平方のリストを作りたいとします:

   >>> squares = []
   >>> for x in range(10):
   ...     squares.append(x**2)
   ...
   >>> squares
   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We can obtain the same result with:

   squares = [x**2 for x in range(10)]

This is also equivalent to "squares = map(lambda x: x**2, range(10))",
but it’s more concise and readable.

リスト内包表記は、括弧の中の 式、 "for" 句、そして0個以上の "for" か
"if" 句で構成されます。リスト内包表記の実行結果は、 "for" と "if" 句の
コンテキスト中で式を評価した結果からなる新しいリストです。例えば、次の
リスト内包表記は2つのリストの要素から、違うもの同士をペアにします:

   >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

"for" と "if" 文が両方のコードで同じ順序になっていることに注目してくだ
さい。

式がタプルの場合 (例: 上の例で式が "(x, y)" の場合) は、タプルに円括弧
が必要です。

   >>> vec = [-4, -2, 0, 2, 4]
   >>> # create a new list with the values doubled
   >>> [x*2 for x in vec]
   [-8, -4, 0, 4, 8]
   >>> # filter the list to exclude negative numbers
   >>> [x for x in vec if x >= 0]
   [0, 2, 4]
   >>> # apply a function to all the elements
   >>> [abs(x) for x in vec]
   [4, 2, 0, 2, 4]
   >>> # call a method on each element
   >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
   >>> [weapon.strip() for weapon in freshfruit]
   ['banana', 'loganberry', 'passion fruit']
   >>> # create a list of 2-tuples like (number, square)
   >>> [(x, x**2) for x in range(6)]
   [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
   >>> # the tuple must be parenthesized, otherwise an error is raised
   >>> [x, x**2 for x in range(6)]
     File "<stdin>", line 1, in <module>
       [x, x**2 for x in range(6)]
                  ^
   SyntaxError: invalid syntax
   >>> # flatten a list using a listcomp with two 'for'
   >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
   >>> [num for elem in vec for num in elem]
   [1, 2, 3, 4, 5, 6, 7, 8, 9]

リスト内包表記の式には、複雑な式や関数呼び出しのネストができます:

   >>> from math import pi
   >>> [str(round(pi, i)) for i in range(1, 6)]
   ['3.1', '3.14', '3.142', '3.1416', '3.14159']


ネストしたリストの内包表記
~~~~~~~~~~~~~~~~~~~~~~~~~~

リスト内包表記中の最初の式は任意の式なので、そこに他のリスト内包表記を
書くこともできます。

次の、長さ4のリスト3つからなる、3x4 の matrix について考えます:

   >>> matrix = [
   ...     [1, 2, 3, 4],
   ...     [5, 6, 7, 8],
   ...     [9, 10, 11, 12],
   ... ]

次のリスト内包表記は、matrix の行と列を入れ替えます:

   >>> [[row[i] for row in matrix] for i in range(4)]
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

前の節で見たように、ネストしたリスト内包表記は、続く "for" のコンテキ
ストの中で評価されます。なので、この例は次のコードと等価です:

   >>> transposed = []
   >>> for i in range(4):
   ...     transposed.append([row[i] for row in matrix])
   ...
   >>> transposed
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

これをもう一度変換すると、次のコードと等価になります:

   >>> transposed = []
   >>> for i in range(4):
   ...     # the following 3 lines implement the nested listcomp
   ...     transposed_row = []
   ...     for row in matrix:
   ...         transposed_row.append(row[i])
   ...     transposed.append(transposed_row)
   ...
   >>> transposed
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

実際には複雑な流れの式よりも組み込み関数を使う方が良いです。この場合
"zip()" 関数が良い仕事をしてくれるでしょう:

   >>> zip(*matrix)
   [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

この行にあるアスタリスクの詳細については 引数リストのアンパック を参照
してください。


"del" 文
========

リストから要素を削除する際、値を指定する代わりにインデックスを指定する
方法があります。それが "del" 文です。これは "pop()" メソッドと違い、値
を返しません。 "del" 文はリストからスライスを除去したり、リスト全体を
削除することもできます(以前はスライスに空のリストを代入して行っていま
した)。例えば以下のようにします:

   >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
   >>> del a[0]
   >>> a
   [1, 66.25, 333, 333, 1234.5]
   >>> del a[2:4]
   >>> a
   [1, 66.25, 1234.5]
   >>> del a[:]
   >>> a
   []

"del" は変数全体の削除にも使えます:

   >>> del a

この文の後で名前 "a" を参照すると、(別の値を "a" に代入するまで) エラ
ーになります。 "del" の別の用途についてはまた後で取り上げます。


タプルとシーケンス
==================

リストや文字列には、インデクスやスライスを使った演算のように、数多くの
共通の性質があることを見てきました。これらは *シーケンス (sequence)*
データ型 (Sequence Types — str, unicode, list, tuple, bytearray,
buffer, xrange を参照) の二つの例です。 Python はまだ進歩の過程にある
言語なので、他のシーケンスデータ型が追加されるかもしれません。標準のシ
ーケンス型はもう一つあります: *タプル (tuple)* 型です。

タプルはコンマで区切られたいくつかの値からなります。例えば以下のように
書きます:

   >>> t = 12345, 54321, 'hello!'
   >>> t[0]
   12345
   >>> t
   (12345, 54321, 'hello!')
   >>> # Tuples may be nested:
   ... u = t, (1, 2, 3, 4, 5)
   >>> u
   ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
   >>> # Tuples are immutable:
   ... t[0] = 88888
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: 'tuple' object does not support item assignment
   >>> # but they can contain mutable objects:
   ... v = ([1, 2, 3], [3, 2, 1])
   >>> v
   ([1, 2, 3], [3, 2, 1])

ご覧のとおり、タプルの表示には常に丸括弧がついていて、タプルのネストが
正しく解釈されるようになっています。タプルを書くときは必ずしも丸括弧で
囲まなくてもいいですが、(タプルが大きな式の一部だった場合は) 丸括弧が
必要な場合もあります。タプルの要素を代入することはできません。しかし、
タプルにリストのような変更可能型を含めることはできます。

タプルはリストと似ていますが、たいてい異なる場面と異なる目的で利用され
ます。タプルは不変型 (*immutable*) で、複数の型の要素からなることもあ
り、要素はアンパック(この節の後半に出てきます)操作やインデックス (ある
いは "namedtuples" の場合は属性)でアクセスすることが多いです。一方、リ
ストは変更可能 (*mutable*) で、要素はたいてい同じ型のオブジェクトであ
り、たいていイテレートによってアクセスします。

問題は 0 個または 1 個の項目からなるタプルの構築です。これらの操作を行
うため、構文には特別な細工がされています。空のタプルは空の丸括弧ペアで
構築できます。一つの要素を持つタプルは、値の後ろにコンマを続ける (単一
の値を丸括弧で囲むだけでは不十分です) ことで構築できます。美しくはない
けれども、効果的です。例えば以下のようにします:

   >>> empty = ()
   >>> singleton = 'hello',    # <-- note trailing comma
   >>> len(empty)
   0
   >>> len(singleton)
   1
   >>> singleton
   ('hello',)

文 "t = 12345, 54321, 'hello!'" は *タプルのパック (tuple packing)* の
例です。値 "12345", "54321", "'hello!'" が一つのタプルにパックされます
。逆の演算も可能です:

   >>> x, y, z = t

This is called, appropriately enough, *sequence unpacking* and works
for any sequence on the right-hand side.  Sequence unpacking requires
the list of variables on the left to have the same number of elements
as the length of the sequence.  Note that multiple assignment is
really just a combination of tuple packing and sequence unpacking.


集合型
======

Python には、 *集合 (set)* を扱うためのデータ型もあります。集合とは、
重複する要素をもたない、順序づけられていない要素の集まりです。 Set オ
ブジェクトは、和 (union)、積 (intersection)、差 (difference)、対称差
(symmetric difference)といった数学的な演算もサポートしています。

中括弧、または "set()" 関数は set を生成するために使用することができま
す。注: 空集合を作成するためには "set()" を使用しなければなりません
("{}" ではなく)。後者は空の辞書を作成します。辞書は次のセクションで議
論するデータ構造です。

簡単なデモンストレーションを示します:

   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
   >>> fruit = set(basket)               # create a set without duplicates
   >>> fruit
   set(['orange', 'pear', 'apple', 'banana'])
   >>> 'orange' in fruit                 # fast membership testing
   True
   >>> 'crabgrass' in fruit
   False

   >>> # Demonstrate set operations on unique letters from two words
   ...
   >>> a = set('abracadabra')
   >>> b = set('alacazam')
   >>> a                                  # unique letters in a
   set(['a', 'r', 'b', 'c', 'd'])
   >>> a - b                              # letters in a but not in b
   set(['r', 'd', 'b'])
   >>> a | b                              # letters in either a or b
   set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
   >>> a & b                              # letters in both a and b
   set(['a', 'c'])
   >>> a ^ b                              # letters in a or b but not both
   set(['r', 'd', 'b', 'm', 'z', 'l'])

リスト内包 と同様に、 set 内包もサポートされています:

   >>> a = {x for x in 'abracadabra' if x not in 'abc'}
   >>> a
   set(['r', 'd'])


辞書型 (dictionary)
===================

もう一つ、有用な型が Python に組み込まれています。それは *辞書
(dictionary)* (マッピング型 — dict を参照)です。辞書は他の言語にも 「
連想記憶 (associated memory)」 や 「連想配列 (associative array)」 と
いう名前で存在することがあります。ある範囲の数でインデクス化されている
シーケンスと異なり、辞書は *キー (key)* でインデクス化されています。こ
のキーは何らかの変更不能な型になります。文字列、数値は常にキーにするこ
とができます。タプルは、文字列、数値、その他のタプルのみを含む場合はキ
ーにすることができます。直接、あるいは間接的に変更可能なオブジェクトを
含むタプルはキーにできません。リストをキーとして使うことはできません。
これは、リストにスライスやインデクス指定の代入を行ったり、 "append()"
や "extend()" のようなメソッドを使うと、インプレースで変更することがで
きるためです。

辞書は順序付けのされていない *キー(key): 値(value)* のペアの集合であり
、キーが (辞書の中で)一意でければならない、と考えるとよいでしょう。波
括弧 (brace) のペア: "{}" は空の辞書を生成します。カンマで区切られた
key: value のペアを波括弧ペアの間に入れると、辞書の初期値となる key:
value が追加されます; この表現方法は出力時に辞書が書き出されるのと同じ
方法です。

辞書での主な操作は、ある値を何らかのキーを付けて記憶することと、キーを
指定して値を取り出すことです。 "del" で key: value のペアを削除するこ
ともできます。すでに使われているキーを使って値を記憶すると、以前そのキ
ーに関連づけられていた値は忘れ去られてしまいます。存在しないキーを使っ
て値を取り出そうとするとエラーになります。

The "keys()" method of a dictionary object returns a list of all the
keys used in the dictionary, in arbitrary order (if you want it
sorted, just apply the "sorted()" function to it).  To check whether a
single key is in the dictionary, use the "in" keyword.

以下に、辞書を使った簡単な例を示します:

   >>> tel = {'jack': 4098, 'sape': 4139}
   >>> tel['guido'] = 4127
   >>> tel
   {'sape': 4139, 'guido': 4127, 'jack': 4098}
   >>> tel['jack']
   4098
   >>> del tel['sape']
   >>> tel['irv'] = 4127
   >>> tel
   {'guido': 4127, 'irv': 4127, 'jack': 4098}
   >>> tel.keys()
   ['guido', 'irv', 'jack']
   >>> 'guido' in tel
   True

"dict()" コンストラクタは、キーと値のペアのタプルを含むリストから辞書
を生成します:

   >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
   {'sape': 4139, 'jack': 4098, 'guido': 4127}

さらに、辞書内包表現を使って、任意のキーと値のペアから辞書を作れます:

   >>> {x: x**2 for x in (2, 4, 6)}
   {2: 4, 4: 16, 6: 36}

キーが単純な文字列の場合、キーワード引数を使って定義する方が単純な場合
もあります:

   >>> dict(sape=4139, guido=4127, jack=4098)
   {'sape': 4139, 'jack': 4098, 'guido': 4127}


ループのテクニック
==================

シーケンスにわたるループを行う際、 "enumerate()" 関数を使うと、要素の
インデックスと要素を同時に取り出すことができます。

   >>> for i, v in enumerate(['tic', 'tac', 'toe']):
   ...     print i, v
   ...
   0 tic
   1 tac
   2 toe

二つまたはそれ以上のシーケンス型を同時にループするために、関数 "zip()"
を使って各要素をひと組みにすることができます。

   >>> questions = ['name', 'quest', 'favorite color']
   >>> answers = ['lancelot', 'the holy grail', 'blue']
   >>> for q, a in zip(questions, answers):
   ...     print 'What is your {0}?  It is {1}.'.format(q, a)
   ...
   What is your name?  It is lancelot.
   What is your quest?  It is the holy grail.
   What is your favorite color?  It is blue.

シーケンスを逆方向に渡ってループするには、まずシーケンスの範囲を順方向
に指定し、次いで関数 "reversed()" を呼び出します。

   >>> for i in reversed(xrange(1,10,2)):
   ...     print i
   ...
   9
   7
   5
   3
   1

シーケンスをソートされた順序でループするには、 "sorted()" 関数を使いま
す。この関数は元の配列を変更せず、ソート済みの新たな配列を返します。

   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
   >>> for f in sorted(set(basket)):
   ...     print f
   ...
   apple
   banana
   orange
   pear

When looping through dictionaries, the key and corresponding value can
be retrieved at the same time using the "iteritems()" method.

   >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
   >>> for k, v in knights.iteritems():
   ...     print k, v
   ...
   gallahad the pure
   robin the brave

ときどきループ内でリストを変更したい誘惑に駆られるでしょうが、代わりに
新しいリストを作ってしまうほうがより簡単で安全なことが、ままあります

   >>> import math
   >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
   >>> filtered_data = []
   >>> for value in raw_data:
   ...     if not math.isnan(value):
   ...         filtered_data.append(value)
   ...
   >>> filtered_data
   [56.2, 51.7, 55.3, 52.5, 47.8]


条件についてもう少し
====================

"while" や "if" 文で使った条件 (condition) には、値の比較だけでなく、
他の演算子も使うことができます。

比較演算子 "in" および "not in" は、ある値があるシーケンス中に存在する
か (または存在しないか) どうかを調べます。演算子 "is" および "is not"
は、二つのオブジェクトが実際に同じオブジェクトであるかどうかを調べます
。この比較は、リストのような変更可能なオブジェクトにだけ意味があります
。全ての比較演算子は同じ優先順位を持っており、ともに数値演算子よりも低
い優先順位となります。(訳注: "is" は、 "is None" のように、シングルト
ンの変更不能オブジェクトとの比較に用いる場合もあります。(「変更可能な
オブジェクトにだけ意味があります」の部分を削除することを Doc-SIG に提
案中。))

比較は連結させることができます。例えば、 "a < b == c" は、 "a" が "b"
より小さく、かつ "b" と "c" が等しいかどうかをテストします。

ブール演算子 "and" や "or" で比較演算を組み合わせることができます。そ
して、比較演算 (あるいは何らかのブール式) の結果の否定は "not" でとれ
ます。これらの演算子は全て、比較演算子よりも低い優先順位になっています
。 "A and not B or C" と "(A and (not B)) or C" が等価になるように、ブ
ール演算子の中で、 "not" の優先順位が最も高く、 "or" が最も低くなって
います。もちろん、丸括弧を使えば望みの組み合わせを表現できます。

ブール演算子 "and" と "or" は、いわゆる *短絡 (short-circuit)* 演算子
です。これらの演算子の引数は左から右へと順に評価され、結果が確定した時
点で評価を止めます。例えば、 "A" と "C" は真で "B" が偽のとき、 "A and
B and C" は式 "C" を評価しません。一般に、短絡演算子の戻り値をブール値
ではなくて一般的な値として用いると、値は最後に評価された引数になります
。

比較や他のブール式の結果を変数に代入することもできます。例えば、

   >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
   >>> non_null = string1 or string2 or string3
   >>> non_null
   'Trondheim'

Python では、C 言語と違って、式の内部で代入を行えないので注意してくだ
さい。 C 言語のプログラマは不満に思うかもしれませんが、この仕様は、 C
言語プログラムで遭遇する、式の中で "==" のつもりで "=" とタイプしてし
まうといったありふれた問題を回避します。


シーケンスとその他の型の比較
============================

Sequence objects may be compared to other objects with the same
sequence type. The comparison uses *lexicographical* ordering: first
the first two items are compared, and if they differ this determines
the outcome of the comparison; if they are equal, the next two items
are compared, and so on, until either sequence is exhausted. If two
items to be compared are themselves sequences of the same type, the
lexicographical comparison is carried out recursively.  If all items
of two sequences compare equal, the sequences are considered equal. If
one sequence is an initial sub-sequence of the other, the shorter
sequence is the smaller (lesser) one.  Lexicographical ordering for
strings uses the ASCII ordering for individual characters.  Some
examples of comparisons between sequences of the same type:

   (1, 2, 3)              < (1, 2, 4)
   [1, 2, 3]              < [1, 2, 4]
   'ABC' < 'C' < 'Pascal' < 'Python'
   (1, 2, 3, 4)           < (1, 2, 4)
   (1, 2)                 < (1, 2, -1)
   (1, 2, 3)             == (1.0, 2.0, 3.0)
   (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Note that comparing objects of different types is legal.  The outcome
is deterministic but arbitrary: the types are ordered by their name.
Thus, a list is always smaller than a string, a string is always
smaller than a tuple, etc. [1] Mixed numeric types are compared
according to their numeric value, so 0 equals 0.0, etc.

-[ 脚注 ]-

[1] The rules for comparing objects of different types should not
    be relied upon; they may change in a future version of the
    language.
