On Jul 20, 12:27 pm, Phillip B Oldham <phillip.old...@gmail.com> wrote: > My colleagues and I have been working with python for around 6 months > now, and while we love a lot of what python has done for us and what > it enables us to do some of the decisions behind such certain > data-types and their related methods baffle us slightly (when compared > to the decisions made in other, similarly powerful languages). > > Specifically the "differences" between lists and tuples have us > confused and have caused many "discussions" in the office. We > understand that lists are mutable and tuples are not, but we're a > little lost as to why the two were kept separate from the start. They > both perform a very similar job as far as we can tell. > > Consider the following: > > >>> x = [2,1,3] > >>> x.sort() > >>> print x > > [1, 2, 3] > > Now, if the sort operations were unable to affect the original > structure of the list (as in JavaScript) you'd effectively have a > tuple which you could add/remove from, and the example above would > look more like: > > >>> x = [2,1,3] > >>> print x.sort() > [1, 2, 3] > >>> print x > > [2,1,3] > > This make a lot more sense to us, and follows the convention from > other languages. It would also mean chaining methods to manipulate > lists would be easier: > > >>> x = [2,1,3] > >>> print x.sort()[0] > 3
(As others have already pointed out this would print 1, not 3.) > >>> print x > > [2,1,3] > > We often find we need to do manipulations like the above without > changing the order of the original list, and languages like JS allow > this. We can't work out how to do this in python though, other than > duplicating the list, sorting, reversing, then discarding. In this case you can use: >>> x = [2,1,3] >>> print min(x) 1 (There's also a max() function.) > We're not looking to start any arguments or religious wars and we're > not asking that python be changed into something its not. We'd simply > like to understand the decision behind the lists and tuple structures. > We feel that in not "getting" the difference between the two types we > may be missing out on using these data structures to their full > potential. One way to think about tuples (as distinct from lists) is as a short- hand version of Pascal's 'record' type, or C's 'struct' (with the caveats that the fields are not named, only indexed, and the types of the fields are implied by use, not explicitly declared.) (FWIW: http://en.wikipedia.org/wiki/Record_(computer_science) ) Broadly speaking, lists are useful for things like stacks and queues, and sorting, while tuples are useful for aggregating heterogeneous data into coherent units, and you can hash them (provided their contents are also hashable.) HTH, ~Simon -- http://mail.python.org/mailman/listinfo/python-list