By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,363 Members | 1,719 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,363 IT Pros & Developers. It's quick & easy.

List and tuple usage distinction??

P: n/a
I am a little confused about a list and a tuple.

Both can have dissimilar data-type elements, can be returned
by functions. The only difference that I see is that list is
mutable and tuple is not (of course list have .append() etc.)

What is a possible scenario where one is preferred over the other?

-ishwar
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Ishwar Rattan wrote:
I am a little confused about a list and a tuple.

Both can have dissimilar data-type elements, can be returned
by functions. The only difference that I see is that list is
mutable and tuple is not (of course list have .append() etc.)

What is a possible scenario where one is preferred over the other?

-ishwar

Lots of reasons ;-)

1. Maybe you want to create a dict and key off of a list of items. I
haven't had to do that, but it's feasible. Take a peek at this:
f = ('a', 'b', 'c')
g = list(f)
f ('a', 'b', 'c') g ['a', 'b', 'c'] h = {}
h[f] = 1
h[g] = 1 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable h {('a', 'b', 'c'): 1}

You can key off of a tuple (the tuple "f") and you can't off of a plain
old list ("g").

2. You don't need the list of items to change or similarly
3. You want to make it more difficult for a list of items to change.
You can still fairly easily change a tuple - sort of: f = list(f)
f.append('d')
f = tuple(f)
f ('a', 'b', 'c', 'd')

What you've actually done is change the tuple object that "f" is
pointing to.

Someone else can answer better about memory usage, but I would think
that a tuple would cost less memory than a comparably sized list, so
that also may be a consideration.

Jeremy

Jul 18 '05 #2

P: n/a
Ishwar Rattan wrote:
I am a little confused about a list and a tuple.

Both can have dissimilar data-type elements, can be returned
by functions. The only difference that I see is that list is
mutable and tuple is not (of course list have .append() etc.)

What is a possible scenario where one is preferred over the other?


Does this answer in the FAQ list help?

http://www.python.org/doc/faq/genera...ist-data-types

-Peter
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.