Lists and Tuples

J

Jeff Wagner

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
 
P

Paul Rubin

Jeff Wagner said:
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.
 
D

David Eppstein

Paul Rubin said:
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.
 
J

Jeff Wagner

Jeff Wagner said:
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
 
A

Andrew Bennetts

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?
Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert',
'__setslice__', 'count', 'remove', '__setitem__', '__iadd__', 'pop',
'__delitem__', 'append', '__imul__'])

;)

-Andrew.
 
D

Dennis Lee Bieber

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...

--
 
D

Douglas Alan

David Eppstein said:
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
dead wrong.

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
 
B

Bengt Richter

Paul Rubin said:
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
 
D

Douglas Alan

X-Draft-From: ("comp.lang.python" 285349)
To: (e-mail address removed) (Bengt Richter)
Subject: Re: Lists and Tuples
References: <[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
Fcc: |rcvstore +articles
From: Douglas Alan <[email protected]>
--text follows this line--
On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein
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
 
J

Joe Francia

Jeff said:
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
 
F

Fredrik Lundh

Douglas said:
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
dead wrong.

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>
 
D

Duncan Booth

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.
 
M

Michael Hudson

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

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
 
D

Dang Griffith

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?
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
 
R

Roy Smith

Jeff Wagner said:
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.
 
R

Roy Smith

Joe Francia said:
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.
 
R

Roy Smith

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:
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().
 
S

Skip Montanaro

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

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

class Address:
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
 
D

David Eppstein

Roy Smith said:
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. ...
 
R

Roy Smith

Skip Montanaro said:
(Probably more response than you wanted. I kind of got carried away...)


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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top