Python Data Structures: Lists vs Tuples

It could be somewhat challenging for beginners to tell the exact difference between lists and tuples as they are similar and can be used in place of each other in some cases. This article discusses similarities and differences between lists and tuples, when to use which, and the advantages of one over the other.

Similarities

  • Lists and tuples are both data structures used to store data.
  • They have similar structures: they hold a mixture of data (elements) in a particular order separated by commas and retrieved by their index.
  • They can hold data of any type, including null types.

Differences

  • Syntax: Lists are enclosed in braces “[ ]”, as opposed to Tuples which are enclosed in parentheses “( )” or written just like that, without parentheses.
  • Mutability: After creation, lists can be changed, modified, and reordered, compared to tuples that are fixed and cannot be altered.

Advantages of immutability (i.e. Tuples over Lists)

  • It is easier to generate errors in modifying the data in Lists than Tuples, which do not allow that. I.e. Fewer errors occur when you use Tuples.
  • Debugging is relatively less challenging due to the immutable nature of Tuples.

Examples

A List should look like this:

Below is an attempt to modify the list above that happens successfully. First, I used the append function to add an element at the end of the list. Then, I used the remove function to delete an element. The result is my initial list plus the appended element minus the removed element.

Code Screenshot: A successful attempt to modify a list.

A Tuple should look like this:

  • With parentheses:
Code Screenshot: A tuple example (with parentheses)
  • Without parentheses:
Code Screenshot: A tuple example (without parentheses)

Attempting to modify the tuple above returns an error, as shown below. It’s a confirmation of its immutability, as stated in previous paragraphs.

Code Screenshot: An attempt to modify a tuple.

When to use which

  • Use Tuples to communicate to your co-worker or the code interpreter that the elements should not be increased or reduced.
  • Use Lists when you expect that the elements would be operated on or required to be altered at some point.
  • Use Lists when you are uncertain about the volume of elements to be stored.
  • Use Tuples when you are not expecting data manipulation and just want to store them for easy access and indexing.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store