7

In python, the list data structure is a sequence of elements. Similarly, a tuple is also a sequence of elements, however, tuples are immutable.

Whats the reason for making such a similar data structure, thats only feature, as opposed to lists, is that it can't be changed? Does it perhaps save memory space, by being immutable?

Also if a list and a tuple contains the exact same data, will they use the same amount of space in the memory?

Daniel Mac
  • 400
  • 2
  • 14
  • Related: [python: list vs tuple, when to use each?](http://stackoverflow.com/questions/1708510/python-list-vs-tuple-when-to-use-each) – Ashwini Chaudhary Sep 19 '13 at 13:07
  • Related: [What's the difference between list and tuples in Python?](http://stackoverflow.com/questions/626759/whats-the-difference-between-list-and-tuples-in-python) – Ashwini Chaudhary Sep 19 '13 at 13:08

1 Answers1

6

Immutable types are hashable, and can be used as dictionary keys. This works:

key = (1, 2, 3)
d = {key: 1}

But this doesn't:

key = [1, 2, 3]
d = {key: 1}

If it did, what would you expect this to do?

key[0] = 2
print d[key]        # id(key) hasn't changed, so surely the lookup should still work
print d[[1, 2, 3]]  # but also, we stored a piece of data at [1, 2, 3], didn't we?
print d[[2, 2, 3]]  # but if d[key] works, surely we can expand key to its value
Eric
  • 95,302
  • 53
  • 242
  • 374