List and tuple usage distinction??
Jeremy Jones
zanesdad at bellsouth.net
Wed Sep 1 21:10:16 EDT 2004
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
More information about the Python-list
mailing list