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.
- 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.
- 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.
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.
A Tuple should look like this:
- With parentheses:
- 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.
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.