1

Possible Duplicate:
What's the difference between list and tuples in Python?

I've got just theoretical question: If I say that tuples are just immutable lists, how am I wrong (or am I not?)?

I know that tuples are immutable for only some level: if I have a tuple with a mutable object in it (list, python object, whatever) - it is somehow mutable, because I can change value of that object, but still - tuple structure, its pointers to elements stays constant, so tuple itself is immutable. I know that, you dont have to explain this.

As far as I get it, besides mutability - there are no differences. For both types operator + returns adequate structure made of elements of operands, in order, += operator works ass well, both can be accessed with simple indexes, or with slices, both responds to len(), map() (this is a little tricky: map(foo, tuple) returns list, not tuple. I think I get the reason for such a behavior, but still its worth mentioning), all(), any(), etc...

So - the same functionality, a little different syntax, main difference in mutability. Is that right? Or did I miss something?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Filip Malczak
  • 3,124
  • 24
  • 44

2 Answers2

1

The traditional differentiation between lists and tuples has been that tuples are meant to be used for heterogeneous data of fixed length, while lists are aimed at homogeneous data of variable length.

This distinguation has been relaxed in recent years. For example tuples got the count() and index() methods that only make sense for homogeneous data, and isinstance(tuple, collections.Sequence) is True.

So in my opinion it's not too far off the mark to think of tuples as immutable lists. Immutability allows them to be hashable, so they can be used as keys in dictionaries and in sets given all items are hashable, but they can't be changed.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

Basically you are right, but the concepts are a little different.

There's a good explanation here: http://news.e-scribe.com/397

Also, there's a similar thread about it here: python: list vs tuple, when to use each?

Community
  • 1
  • 1
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299