[docs] [issue14840] Tutorial: Add a bit on the difference between tuples and lists
Terry J. Reedy
report at bugs.python.org
Fri May 18 00:16:27 CEST 2012
Terry J. Reedy <tjreedy at udel.edu> added the comment:
Zachary, you are brave/foolhardy to take this on;)
I agree that the XXX comment should be removed. One possible resolution is to do just that, replacing it with nothing.
I would note that the fuss over tuples versus lists comes from a time before iterators became a common way to pass around and process sequences. This, in a sense, makes tuples and lists more similar that they were before in that iterators have mostly replaced one of the list uses that made lists different from tuples. We do not fuss over whether an iterator is 'homogeneous' or 'heterogeneous'. Each is, of course, mutable until exhausted.
Another change is that now isinstance(x, object) is True for everything, so that one can now view all concrete collections as homogeneous at the Python level as well as at the C implementation level. Things were different before the unification of types and classes, completed in 3.0.
As to the proposal: I am one of the 'some people'. 'Tends to' helps a lot. Now to be picky.
I would say that tuples and list are similar to each other in being concrete sequences of objects (instances of class <object>). I would remove 'fundamentally'.
The rest of the initial paragraph leaves out the usage of tuples as constant sequences (which is to say, immutable 'all the way down'). First is the hard-coded constant: consider
>>> def f(): return (((1,2),(3,4)),((5,6),(7,8)))
1 0 LOAD_CONST 15 ((((1, 2), (3, 4)), ((5, 6), (7, 8))))
>>> def fl(): return[[[1,2],[3,4]],[[5,6],[7,8]]]
1 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 BUILD_LIST 2
9 LOAD_CONST 3 (3)
12 LOAD_CONST 4 (4)
15 BUILD_LIST 2
18 BUILD_LIST 2
21 LOAD_CONST 5 (5)
24 LOAD_CONST 6 (6)
27 BUILD_LIST 2
30 LOAD_CONST 7 (7)
33 LOAD_CONST 8 (8)
36 BUILD_LIST 2
39 BUILD_LIST 2
42 BUILD_LIST 2
Second are sequences used as keys, regardless of 'geneity.
Third are the homogeneous sequences that the language syntax requires to be tuples, not lists: except, issubclass, isinstance. There are also the typically homogeneous tuples for *args and possibly homogeneous second argument to % interpolation. In other words, the language itself does not support the second sentence.
On the other hand, if one has a heterogeneous list, perhaps from a list comprehension, that will not be hashed, there may be no need other than philosophical purity to convert it to a tuple. Im/mutability is part of the definition and operaton of the language. Homo/heter/geneity is not (that I can think of at the moment).
I do not especially like the suggested add on sentence as is. 'Immutable list' is wrong; a tuple is an immutable sequence, and what one typically needs is a constant (hashable) sequence, and if one does, a tuple is essential, not just 'handy'.
Python tracker <report at bugs.python.org>
More information about the docs