List and tuple usage distinction??

I

Ishwar Rattan

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
 
J

Jeremy Jones

Ishwar said:
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):
{('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: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
 
P

Peter Hansen

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top