Saturday, May 14, 2016

Why Tuples, when Python already has Lists ?

One of my student, very pertinently asked me, "Why do we need Tuples, when we already have a data structure called list ? Tuples are almost same like Lists, except that they are immutable. So, what's such a big deal about being immutable ?"

This question, inspired me to write this post and add some clarity on when to prefer "Tuples" over "Lists" in Python. I am assuming that the basic understanding of what a Tuple is and what a List is more or less understood by the reader, but is not able to decide which one to choose over the other. I intend to concentrate more on situations when it would make more [ programming ? ] sense to use "Tuples" rather than "Lists" to help answer the question.

Few distinctions between "Tuple" and "Lists" are :

  1. List is a data structure for storing and manipulating a collection of items. Tuple is not a data structure in the same sense, even though it helps to store a collection of items.
  2. Lists, by convention are used for storing collection of items that are of the same types [ homogeneous ]. Where as Tuples, by convention are used for storing collection of items that are of different types [ heterogeneous ]. Beware that this is only a coding style preference and the language as such does not support any such restriction.
  3. Individual items in a List can be modified and updated. Tuples are immutable, and thus its individual items cannot be modified or updated.
  4. The number of methods supported in a List are much more than those for a Tuple, since Lists allow us to manipulate its collection of items and thus need a lot more methods to support those manipulations.