79 points · by joshbaptiste · 10y ago · 122 comments
Python is not a language that "gets it", despite the article's examples. Python chooses the much-less-useful distinction between "immutable sequence" and "mutable sequence"; the lack of any other distinction is borne out by the standard library (as dozzie points out here [1]). Furthermore, the issue of immutable vs. mutable is totally orthogonal to that of dynamic/static and homogeneous/heterogeneous. There's no reason that "cultural" lists need be mutable, or "cultural" tuples need be immutable. So Python's choice doesn't make sense from this angle either.
For example, OCaml has both immutable lists and immutable tuples; its type system enforces exactly the "cultural difference". Similarly with C, which has both mutable lists (arrays) and mutable tuples (structs), both of which can be rendered immutable (const). Why Python chose lists (and only lists!) to have both immutable and mutable flavors, with otherwise identical semantics, is beyond me.
Erlang used to "get it", but they lost the thread when they came out with heterogeneous syntax support for a homogeneous structure (map). TLA+ totally conflates tuples with lists, but its type system is rich enough to enforce the difference (and as a bonus, allows for the elusive static homogeneous structure).
That would be a bad idea for at least two reasons: sometimes you want containers to be immutable, and mutable containers can't be used as dictionary keys.
Then again, I also use single and double quotes as a semantic guide to mean different things. I feel like that would probably make most programmers want to throw the computer at the wall, but so it goes
1. TLA+ doesn't conflate the two at all. On the contrary: it has neither. TLA+'s data is based on set theory, and has syntax sugar for mathematical sequences, defined in TLA+ as functions from a prefix of the natural numbers to some set. I don't know what either "lists" or "tuples" are mathematically (in terms of set theory), and neither does TLA+. Like ordinary formal math, TLA+ has only sets (and functions, which are theoretically also encoded sets). Everything else can be defined in those terms. If, you come up with a mathematical definition of either or both, you can use it in TLA+. If the definition is the same for both, they won't will be the same; if it isn't -- they won't.
2. Like "ordinary" math, TLA+ has no type system at all. But you're right that any program property can be described in its simple logic. E.g., you can have a sequence whose all elements are natural numbers, except the prime indices, which are strings:
∀ n ∈ DOMAIN seq : seq[n] ∈ (IF IsPrime(n) THEN STRING ELSE Nat)
Of course, for simple cases of constant-length sequences, you can have: seq ∈ Nat × STRING × Real
or whatever.It didn't. There's frozenset as well. There's been discussion of an immutable dict every so often, but the conclusion is generally that it's unnecessary.
The reason to have an immutable sequence is mostly to serve as dict keys. Same with an immutable set. If you use a mutable sequence as a dict key, you create ambiguity over whether you care about the memory location or the value of the sequence.
Static heterogeneous structures (tuples) have a non-uniform structure, but need not resize. The former harms performance (run-time type info must be kept for each element, though usually few); the latter helps it (most accesses can be compiled to simple pointer arithmetic).
On the other hand, dynamic heterogeneous structures (Python's lists) do not have uniform structure, and must be able to resize. So run-time type info must be preserved (adding memory/access overhead), and accesses can't be optimized at compile time (more runtime machinery). It is to avoid these issues that things like numpy and JavaScript's typed arrays exist.
There is almost never a reason to use a dynamic heterogeneous structure, so they are best avoided. A dynamic heterogeneous collection can neither support indexing a priori known components (since it is dynamic), nor support iteration (since it is heterogeneous). (Note that a collection of objects of different types but with a shared interface is in fact a homogeneous collection of objects with that interface.)
(The final combination is static homogeneous, but these are a subset of both the first two cases, and do not occur often. The only example I can think of are sets of statistics: all statistics have the same type, but there are a fixed number of them which are known at compile time. They can be optimized very well.)
Some of your comments make no sense even given the above, however. For example, Python lists and tuples certainly support iteration.
er, yes there is. if a list is not mutable, doing list.append(something) in a loop would re-initialize the list every loop iteration. the same reason you shouldn't add to a string in a loop, as strings are imitable.
to me, an immutable list is not a list.
list.append(x)
you would say something like list = list.withLast(x)
thus assigning the newly constructed list value back to the variable 'list'.There is a small literature within computer science on efficient implementations of functional data structures. While some tricks are involved, I think it's safe to say it's a solved problem, thanks to people like Chris Okasaki and Phil Bagwell.
There are better choices for general-purpose functional lists.
One more important difference between tuple and list that's worth knowing about: syntax. Ned makes it seem like tuples have the syntax "(x, y)", but they actually have the syntax "x, y".
I find that a lot of Python programmers, even long-time ones, don't realize this important difference. It's what allows one to write code constructions like "x, y = 1, 2" or "return 1, 2".
One needs the parentheses only to "clarify" this syntax in certain cases; for example, as dict keys, the parens are necessary -- "x = {(1, 2): 2}". Although interestingly, for dict lookup, they are not -- "x[1, 2] == 2".
One way I remind myself of this rule is to realize that "x = 1," is the same as "x = (1,)", but "x = (1)" is actually the same as "x = 1". This is quite different from lists, who are syntactically defined by the "[]" brackets, and thus you require them, or a "list()" call, whenever you make lists, making it just that much more heavyweight as a data structure.
Namedtuples are wonderful! It's like a class with only attributes, except you don't have to define a new class and get slapped across the back of your head by more experienced programmers for creating a useless class. Access objects by index, by name, or by iteration. It's very versatile.
that said, writing generic code that works transparently with both namedtuple values and objects can be a bit irritating: e.g. you might want to derive a new value/object from an existing value/object that updates one of the attributes of the value/object.
class Foo(namedtuple('Foo', (...)):
def __repr__(self):
...
Your 'Foo' gets ordering, hashing, comparison, because it derives from 'namedtuple'. It gets '__repr__' too, but in the example I'm overriding that. __slots__ = ()
to your class definition so that instances of Foo keep the small memory footprint benefits do namedtuple.Oh, if only it were so simple! Python itself doesn't understand what the heck tuples are, in that the built-in functions often treat tuples as simply "immutable lists". See isinstance() and issubclass() functions, which expect what's meant to be a list of classes, but you need to pass a tuple. *args is another such example, as the article mentions.
If what Python calls tuples were the thing with structure instead of order, they wouldn't be iterable.
grid[(1,1)] = TrueAlso you can write this as `grid[1, 1] = True`
The following trivial example shows that, at least for very small lists and tuples, except for the fixed overhead of 16 bytes for a tuple vs. 72 bytes for a list they're the same [edit: no it doesn't. I wasn't looking at the diff between a 1-element and 2-element tuple]:
Perhaps there's more to it?
>>> from sys import getsizeof
>>> list = [94]
>>> getsizeof(list)
80
>>> list = [94, 37]
>>> getsizeof(list)
88
>>> list = [94, 37, 21]
>>> getsizeof(list)
96
>>> list = [94, 37, 21, 19]
>>> getsizeof(list)
104
>>> tuple = (94)
>>> getsizeof(tuple)
24
>>> tuple = (94, 37)
>>> getsizeof(tuple)
72
>>> tuple = (94, 37, 21)
>>> getsizeof(tuple)
80
>>> tuple = (94, 37, 21, 19)
>>> getsizeof(tuple)
88 #!/usr/bin/python
from sys import getsizeof
from random import sample
from time import time
l = sample(xrange(10000), 10000)
t = tuple(l)
print "The tuple's size is " + str(getsizeof(t)) + " and the list's size is " + str(getsizeof(l))
s = time()
z = 0
for x in l:
z += x
print "Iterating through a 10,000 element list took " + str(time() - s) + " seconds."
s = time()
z = 0
for x in t:
z += x
print "Iterating through a 10,000 element tuple took " + str(time() - s) + " seconds."
doug@supermicro:~$ ./x
The tuple's size is 80056 and the list's size is 80072
Iterating through a 10,000 element list took 0.00589299201965 seconds.
Iterating through a 10,000 element tuple took 0.00538778305054 seconds.
doug@supermicro:~$ ./x
The tuple's size is 80056 and the list's size is 80072
Iterating through a 10,000 element list took 0.00553607940674 seconds.
Iterating through a 10,000 element tuple took 0.00536203384399 seconds. C:\Temp>python listtuple.py
The tuple's size is 80048 and the list's size is 80064
Iterating through a 10,000 element list took 0.0005006790161132812 seconds.
Iterating through a 10,000 element tuple took 0.0005006790161132812 seconds.
C:\Temp>python listtuple.py
The tuple's size is 80048 and the list's size is 80064
Iterating through a 10,000 element list took 0.0020074844360351562 seconds.
Iterating through a 10,000 element tuple took 0.001031637191772461 seconds.
C:\Temp>python listtuple.py
The tuple's size is 80048 and the list's size is 80064
Iterating through a 10,000 element list took 0.0 seconds.
Iterating through a 10,000 element tuple took 0.001001596450805664 seconds. mb:~ doug$ ./listtuple
The tuple's size is 40028 and the list's size is 40036
Iterating through a 10,000 element list took 0.00113916397095 seconds.
Iterating through a 10,000 element tuple took 0.00111603736877 seconds.
mb:~ doug$ ./listtuple
The tuple's size is 40028 and the list's size is 40036
Iterating through a 10,000 element list took 0.00126791000366 seconds.
Iterating through a 10,000 element tuple took 0.00133585929871 seconds.
mb:~ doug$ ./listtuple
The tuple's size is 40028 and the list's size is 40036
Iterating through a 10,000 element list took 0.00114607810974 seconds.
Iterating through a 10,000 element tuple took 0.00117492675781 seconds.Because Python is so dynamic, you can't make lists or tuples much better. However, in a static language (like Java or OCaml), you can greatly shrink the size of "cultural" lists by hoisting the (identical) run-time type info out of the elements and into the container. (OCaml does this with floats.) And "cultural" tuples typically can use much simpler implementations, since their sizes are fixed and known at compile time. (C structs are often optimized away entirely in optimized assembly.)
>>> tuple = (94,)
>>> getsizeof(tuple)
64The way you look at a statement like (a,b) = (2,3) is that this is a normal assignment, where you imagine there are one value flowing in the equal sign, from right to left. But it happens to contain two values within its wrap.
In the case of the mutable initial value problem, that's just a choice of semantics (in my opinion, a very bad choice). Without having looked at the implementation, I would assume that if you have no backwards-compatibility concerns, a fix would take a few minutes.
In the case of sets/frozensets, most Python programmers want their sets to be mutable, in a syntax-sugar-y way that's incompatible with using functional persistent data structures.
> most Python programmers want their sets to be mutable
They're accustomed to mutable sets because those are all they've known. But ask a Clojure programmer how they feel about functional collections, and you'll be told they're fine. Functional collections are actually easier to use because you don't have to worry about unintended aliasing.
And functional behavior is not strange at all. No programming language I have ever used (and it's a long list) has used shared, mutable semantics for numbers. Consider, in C:
int a = 3;
int b = a;
b++;
After this code sequence, 'a' is still 3, of course! Nobody with programming experience expects 'a' to be incremented at the same time 'b' is; it's not even something you stop to think about -- it's completely automatic. This is true even though I wrote 'b++' rather than 'b = b + 1' -- 'b++' could more easily be misread as a mutating operation on a shared integer object, like 's.add(x)'. However, there's no language I'm aware of in which that's what it means. (You can introduce aliasing intentionally in C++ with a reference, but this requires an explicit '&' in the code.)For example:
> Another conflict between the Technical and the Cultural: there are places in Python itself where a tuple is used when a list makes more sense. When you define a function with args, args is passed to you as a tuple, even though the position of the values isn't significant, at least as far as Python knows
This is the C behavior of tuple usage being exposed to the Python side. If one explores the C API it becomes clear that an implementation detail of C is being exposed to Python.
> The Cultural Difference is about how lists and tuples are actually used: lists are used where you have a homogenous sequence of unknown length; tuples are used where you know the number of elements in advance because the position of the element is semantically significant.
Here the Culture has moved away from the Technical roots of Python and now they're at odds. On the C side tuples are
not* just used when the length is known ahead of time - tuples are not always immutable on the C side.The context is important if you really want to understand.