# Lists and Tuples

Discussion in 'Python' started by Jeff Wagner, Dec 5, 2003.

1. ### Jeff WagnerGuest

I've spent most of the day playing around with lists and tuples to get a really good grasp on what
you can do with them. I am still left with a question and that is, when should you choose a list or
a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
than just that. Everything I tried with a list worked the same with a tuple. So, what's the
difference and why choose one over the other?

Jeff

Jeff Wagner, Dec 5, 2003

2. ### Paul RubinGuest

Jeff Wagner <> writes:
> I've spent most of the day playing around with lists and tuples to
> get a really good grasp on what you can do with them. I am still
> left with a question and that is, when should you choose a list or a
> tuple? I understand that a tuple is immutable and a list is mutable
> but there has to be more to it than just that. Everything I tried
> with a list worked the same with a tuple. So, what's the difference
> and why choose one over the other?

Try this with a list:

a = [1, 2, 3, 4, 5]
a[3] = 27
print a

Then try it with a tuple.

Paul Rubin, Dec 5, 2003

3. ### David EppsteinGuest

In article <>,
Paul Rubin <http://> wrote:

> Try this with a list:
>
> a = [1, 2, 3, 4, 5]
> a[3] = 27
> print a
>
> Then try it with a tuple.

That's true, but another answer is: you should use tuples for short
sequences of diverse items (like the arguments to a function). You
should use lists for longer sequences of similar items.

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science

David Eppstein, Dec 5, 2003
4. ### Jeff WagnerGuest

On 04 Dec 2003 21:31:12 -0800, Paul Rubin <http://> wrotf:

>Jeff Wagner <> writes:
>> I've spent most of the day playing around with lists and tuples to
>> get a really good grasp on what you can do with them. I am still
>> left with a question and that is, when should you choose a list or a
>> tuple? I understand that a tuple is immutable and a list is mutable
>> but there has to be more to it than just that. Everything I tried
>> with a list worked the same with a tuple. So, what's the difference
>> and why choose one over the other?

>
>
>Try this with a list:
>
> a = [1, 2, 3, 4, 5]
> a[3] = 27
> print a
>
>Then try it with a tuple.

That's because a tuple is immutable and a list is mutable but what else? I guess I said everything I
tried with a tuple worked with a list ... not mentioning I didn't try to break the immutable/mutable
rule I was aware of. Besides trying to change a tuple, I could cut it, slice and dice it just like I
could a list. They seemed to have the same built-in methods, too.

From what I can see, there is no reason for me to ever want to use a tuple and I think there is
something I am missing. Why would Guido go to all the effort to include tuples if (as it appears)
lists are just as good but more powerful ... you can change the contents of a list.

Jeff

Jeff Wagner, Dec 5, 2003
5. ### Andrew BennettsGuest

On Fri, Dec 05, 2003 at 05:19:33AM +0000, Jeff Wagner wrote:
> I've spent most of the day playing around with lists and tuples to get a really good grasp on what
> you can do with them. I am still left with a question and that is, when should you choose a list or
> a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
> than just that. Everything I tried with a list worked the same with a tuple. So, what's the
> difference and why choose one over the other?

What's the difference?

>>> import sets
>>> sets.Set(dir(list)).difference(sets.Set(dir(tuple)))

Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert',
'__setslice__', 'count', 'remove', '__setitem__', '__iadd__', 'pop',
'__delitem__', 'append', '__imul__'])

-Andrew.

Andrew Bennetts, Dec 5, 2003
6. ### Dennis Lee BieberGuest

Jeff Wagner fed this fish to the penguins on Thursday 04 December 2003
21:19 pm:

> tuple. So, what's the difference and why choose one over the other?
>

A tuple can be the key for a dictionary, a list can't.

Not sure of a tuple containing a list, though...

--
> ============================================================== <
> | Wulfraed Dennis Lee Bieber KD6MOG <
> | Bestiaria Support Staff <
> ============================================================== <

Dennis Lee Bieber, Dec 5, 2003
7. ### Douglas AlanGuest

David Eppstein <> writes:

> That's true, but another answer is: you should use tuples for short
> sequences of diverse items (like the arguments to a function). You
> should use lists for longer sequences of similar items.

I disagree. You should use a tuple when you wish to not change the
contents once you have constructed the sequence, and otherwise you
should use a list. Using a tuple can make your code clearer by
letting the reader know from the beginning that the contents won't be
changing.

Fredrik Lundh actually called me names a couple years back for
asserting this, but Python luminary (and rude fellow) or not, he is

You don't have to take my word for it, though, since Python itself
uses tuples in this manner, in the form of the container used for
excess arguments (excess arguments certainly don't have to be short,
and they are generally homogeneous, not heterogeneous), and Python
Mega Widgets (for example) is littered with code that looks like:

optiondefs = (
('initwait', 500, None), # milliseconds
('label_background', 'lightyellow', None),
('label_foreground', 'black', None),
('label_justify', 'left', None),
('master', 'parent', None),
('relmouse', 'none', self._relmouse),
('state', 'both', self._state),
('statuscommand', None, None),
('xoffset', 20, None), # pixels
('yoffset', 1, None), # pixels
('hull_highlightthickness', 1, None),
('hull_highlightbackground', 'black', None),
)

In the above case we see tuples being used both as records *and* as an
arbitrary-length sequence of homogenious elements. Why is a tuple
being used in the latter case, rather than a list? Because the
sequence isn't going to be modified.

|>oug

Douglas Alan, Dec 5, 2003
8. ### Bengt RichterGuest

On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein <> wrote:

>In article <>,
> Paul Rubin <http://> wrote:
>
>> Try this with a list:
>>
>> a = [1, 2, 3, 4, 5]
>> a[3] = 27
>> print a
>>
>> Then try it with a tuple.

>
>That's true, but another answer is: you should use tuples for short
>sequences of diverse items (like the arguments to a function). You
>should use lists for longer sequences of similar items.
>

I'm curious what you're getting at. I.e., what does diversity or
similarity have to do with the choice? Is that an aesthetic thing?
(In which case 'should' should be qualified a bit, IWT ;-)
Or what am I missing?

Regards,
Bengt Richter

Bengt Richter, Dec 5, 2003
9. ### Douglas AlanGuest

X-Draft-From: ("comp.lang.python" 285349)
To: (Bengt Richter)
Subject: Re: Lists and Tuples
References: <>
<>
<>
<bqpfde\$426\$0@216.39.172.122>
Fcc: |rcvstore +articles
From: Douglas Alan <>
--text follows this line--
(Bengt Richter) writes:

> On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein
> <> wrote:

>> That's true, but another answer is: you should use tuples for short
>> sequences of diverse items (like the arguments to a function). You
>> should use lists for longer sequences of similar items.

> I'm curious what you're getting at. I.e., what does diversity or
> similarity have to do with the choice?

Nothing really, except by idiom. When people use "should" here, I
think they are over-generalizing. Most of the time, records (short
and heterogenious) are used in a read-only fashion, and long
homogenous sequences are used in a read-write fashion. But when
people characterize this tendency with a "should", I think they are
making a thinko. There are times when you need to modify a record and
consequently might use a dictionary or list, rather than a tuple,
and there are also times when you will never want to modify a long,
homogenous sequence, in which case many people would find it more
elegant to use a tuple than to use a list.

The reason for the "should" is probably because, I imagine, Guido had
in mind mostly multiple return values from function, and the like,
when he put tuples into the language.

|>oug

Douglas Alan, Dec 5, 2003
10. ### Joe FranciaGuest

Jeff Wagner wrote:
> I've spent most of the day playing around with lists and tuples to get a really good grasp on what
> you can do with them. I am still left with a question and that is, when should you choose a list or
> a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
> than just that. Everything I tried with a list worked the same with a tuple. So, what's the
> difference and why choose one over the other?
>

According to the Python FAQ:

------------------------------------------------------------------------
4.15 Why are there separate tuple and list data types?

Lists and tuples, while similar in many respects, are generally used in
fundamentally different ways. Tuples can be thought of as being similar
to Pascal records or C structs; they're small collections of related
data which may be of different types which are operated on as a group.
For example, a Cartesian coordinate is appropriately represented as a
tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They
tend to hold a varying number of objects all of which have the same type
and which are operated on one-by-one. For example, os.listdir('.')
returns a list of strings representing the files in the current
directory. Functions which operate on this output would generally not
break if you added another file or two to the directory.

Tuples are immutable, meaning that once a tuple has been created, you
can't replace any of its elements with a new value. Lists are mutable,
meaning that you can always change a list's elements. Only immutable
elements can be used as dictionary keys, and hence only tuples and not
lists can be used as keys.

http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
------------------------------------------------------------------------

Of course, this information will prevent neither flame wars, nor you
from using them how you wish (within the boundaries of the language).
However you choose to use them, just be clear and consistent.

Peace,
Joe

Joe Francia, Dec 5, 2003
11. ### Fredrik LundhGuest

Douglas Alan wrote:

> I disagree. You should use a tuple when you wish to not change the
> contents once you have constructed the sequence, and otherwise you
> should use a list.

> Fredrik Lundh actually called me names a couple years back for
> asserting this, but Python luminary (and rude fellow) or not, he is

I'm never dead wrong.

Guido van Rossum, "State of the Python Union", March 2003:
http://www.python.org/doc/essays/ppt/pycon2003/pycon2003.ppt

...

+ It's a matter of user education

+ Example: lists vs. tuples

this is often misrepresented as "tuple are readonly lists",
which is *wrong*

use cases are quite different

*but*... tuples also usable as readonly lists

...

I expect an apology.

</F>

Fredrik Lundh, Dec 5, 2003
12. ### Duncan BoothGuest

Jeff Wagner <> wrote in
news::

> From what I can see, there is no reason for me to ever want to use a
> tuple and I think there is something I am missing. Why would Guido go
> to all the effort to include tuples if (as it appears) lists are just
> as good but more powerful ... you can change the contents of a list.

The most practical difference (if you don't need to modify the contents) is
that tuples can be used as dictionary keys, but lists cannot. There is a
minor performance difference, in particular tuples will take less memory so
if you have a few million of them kicking around your application you might
notice the difference.

However, as other posters have suggested the best way to look at it is
often to use tuples when you have a fixed number of objects, possibly of
different types, e.g. a database record. When you have a variable number of
objects (usually of the same type, or supporting a similar interface) then
a list if obviously better. If you have a variable number of groups of
objects, then a list of tuples seems to fit best. In any of these cases you
could use a list in place of the tuple, but the distinction can help keep
things clear.

Bottom line:

If you are primarily reading the sequence using constant indices, then use
a tuple. If the code starts looking messy then consider defining a class to
replace the tuples and using fieldnames instead of constant indices.

If you need to use the object as a dictionary key, or if you have reason to
be concerned about memory use (because there are a lot of them) use a
tuple.

Otherwise use a list.

--
Duncan Booth
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

Duncan Booth, Dec 5, 2003
13. ### Michael HudsonGuest

Dennis Lee Bieber <> writes:

> Jeff Wagner fed this fish to the penguins on Thursday 04 December 2003
> 21:19 pm:
>
> > tuple. So, what's the difference and why choose one over the other?
> >

> A tuple can be the key for a dictionary, a list can't.
>
>
> Not sure of a tuple containing a list, though...

Nope. A tuple is hashable iff all of its elements are.

Cheers,
mwh

--
Now this is what I don't get. Nobody said absolutely anything
bad about anything. Yet it is always possible to just pull
random flames out of ones ass.

Michael Hudson, Dec 5, 2003
14. ### Dang GriffithGuest

On Fri, 5 Dec 2003 16:59:57 +1100, Andrew Bennetts
<> wrote:

>On Fri, Dec 05, 2003 at 05:19:33AM +0000, Jeff Wagner wrote:
>> I've spent most of the day playing around with lists and tuples to get a really good grasp on what
>> you can do with them. I am still left with a question and that is, when should you choose a list or
>> a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
>> than just that. Everything I tried with a list worked the same with a tuple. So, what's the
>> difference and why choose one over the other?

>
>What's the difference?
>
>>>> import sets
>>>> sets.Set(dir(list)).difference(sets.Set(dir(tuple)))

>Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert',
>'__setslice__', 'count', 'remove', '__setitem__', '__iadd__', 'pop',
>'__delitem__', 'append', '__imul__'])
>
>
>
>-Andrew.
>

I like that--ask a simple question, get a simple answer. Why can't
they all be so straightforward.
--dang

Dang Griffith, Dec 5, 2003
15. ### Roy SmithGuest

In article <>,
Jeff Wagner <> wrote:

> I've spent most of the day playing around with lists and tuples to get a
> really good grasp on what
> you can do with them. I am still left with a question and that is, when
> should you choose a list or
> a tuple? I understand that a tuple is immutable and a list is mutable but
> there has to be more to it
> than just that. Everything I tried with a list worked the same with a tuple.
> So, what's the
> difference and why choose one over the other?
>
> Jeff

The big difference is that tuples (because they are immutable) can be
used as dictionary keys.

So, if you are going to use it as a key, it's got to be a tuple. If
you're going to want to add/delete/change items in it, it's got to be a
list.

If you will never change it, but have no syntatic constraint forcing it
to be immutable, you can pick whichever turns you on. From a stylistic
point of view, I tend to think of tuples when I need to bundle up a
collection of related items (such as a function returning multiple
items). Lists make me think of number of the same kind of item.

Roy Smith, Dec 5, 2003
16. ### Roy SmithGuest

Joe Francia <> wrote:
> For example, a Cartesian coordinate is appropriately represented as a
> tuple of two or three numbers.

I would agree if you're explicitly talking about 2-space or 3-space.
But if you're dealing with higher-order geometries, then a coordinate
becomes an N-vector and now it starts to feel more like a list than a
tuple.

I can't put any rigorous argument behind that, it's just what (to me)
feels right.

Roy Smith, Dec 5, 2003
17. ### Roy SmithGuest

I just stumbled upon an interesting tuple/list dichotomy.

The new isinstance() function can take a tuple (but not a list) as its
second argument. Why? Logically, it should take any sequence. The
operation it's doing is essentially:

for aType in sequence:
if isinstance (thing, aType):
return True
return False

I don't see any reason it should reject a list, but it does:

>>> isinstance (1, [str, int])

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes
and types

This is documented, but it still seems strange. Why go out of your way
to reject a list when a list is really a perfectly reasonable thing to
pass in that context?

Same deal with issubclass().

Roy Smith, Dec 5, 2003
18. ### Skip MontanaroGuest

(Probably more response than you wanted. I kind of got carried away...)

>> I've spent most of the day playing around with lists and tuples to
>> get a really good grasp on what you can do with them. I am still left
>> with a question and that is, when should you choose a list or a
>> tuple?

Generally, choose between tuples and lists based upon your data. In
situations where you have a small, fixed collection of objects of possibly
differing types, use a tuple. In situations where have a collection of
objects of uniform type which might grow or shrink, use a list. For
example, an address might best be represented as a tuple:

itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201")
caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866")

Though all elements are actually strings, they are conceptually different
types. It probably makes no sense to define itcs as

itcs = ("2020 Ridge Avenue", "60201", "IL", "Evanston")

If you are reading test scores from a file, you'd likely accumulate them
into a list:

scores = []
for line in file("foo"):
scores.append(float(line.strip()))

then operate on them as a group, possibly normalized to the list's length:

nscores = len(scores)
mean = sum(scores)/nscores
variance = sum([(n-mean)**2 for n in scores])/nscores
print "Mean:", mean
print "Variance:", variance

Unlike tuples, it's often perfectly reasonable to reorder lists without any
loss of meaning:

scores.sort()
print "Min:", scores[0]
print "Max:", scores[-1]
print "Median:", scores[nscores/2:nscores/2+1]

Think of lists as arrays and tuples as Pascal records or C structs and
you'll probably choose correctly most of the time.

If you want to associate methods with your tuples (similarly for lists), you
should probably define a class instead:

import latlong

def __init__(self, street, city, state, zip):
self.street = street
self.city = city
self.state = state
self.zip = zip

def distance(self, other):
return latlong.cdistance("%s, %s" % (self.city, self.state),
"%s, %s" % (other.city, other.state))

itcs = Address("2020 Ridge Avenue", "Evanston", "IL", "60201")
caffe_lena = Address("47 Phila Street", "Saratoga Springs", "NY", "12866")
print itcs.distance(caffe_lena), "miles"

For the curious, when run, the above prints:

961.976657911 miles

Looks like I won't be attending a concert at Caffe Lena tonight.

(latlong is a module I wrote for use in the Mojam and Musi-Cal websites but
never released publically.)

Skip

Skip Montanaro, Dec 5, 2003
19. ### David EppsteinGuest

In article <>,
Roy Smith <> wrote:

> The new isinstance() function can take a tuple (but not a list) as its
> second argument. Why? Logically, it should take any sequence.

What should it do if the second argument is a type object that is also
iterable?

E.g. suppose that iter(bool) produced the sequence True, False. ...

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science

David Eppstein, Dec 5, 2003
20. ### Roy SmithGuest

In article <>,
Skip Montanaro <> wrote:

> (Probably more response than you wanted. I kind of got carried away...)
>
> >> I've spent most of the day playing around with lists and tuples to
> >> get a really good grasp on what you can do with them. I am still left
> >> with a question and that is, when should you choose a list or a
> >> tuple?

>
> Generally, choose between tuples and lists based upon your data. In
> situations where you have a small, fixed collection of objects of possibly
> differing types, use a tuple. In situations where have a collection of
> objects of uniform type which might grow or shrink, use a list. For
> example, an address might best be represented as a tuple:
>
> itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201")
> caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866")
>
> Though all elements are actually strings, they are conceptually different
> types.

That's a good example, because it makes for a nice segue. If you were
holding data from a form that looked like:

Street: ___________________________
City: ___________________________
State: ___________________________
Zip: ___________________________

Then I agree you're looking at a 4-tuple (assuming you didn't want to go
whole-hog and define an Address class). But, imagine a somewhat more
generic form that looked like:

Address line 1: ________________________
Address line 2: ________________________
Address line 3: ________________________
Address line 4: ________________________

You might fill in exactly the same data, but now if feels like it should
be a list.

Roy Smith, Dec 5, 2003