In Python, lists and tuples are two built-in data types. Conceptually they are very similar, but there is some difference.
First, the lists are mutable. This means that once you have defined a list, you can modify it.
For example,
>>> l = ['a', 'b', 'c']
>>> l[1] = 'x'
>>> print(l)
['a', 'x', 'c']
You can modify the list without any problems.
On the contrary, tuples are immutable. After creating a tuple, you cannot modify it. If you try to modify a tuple you will get an error, as shown in the following example:
l = ('a', 'b', 'c')
l[1] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Tuples have an advantage over lists. They are more memory efficient and time efficient than the lists. This means that using a tuple to store a set of items will require less memory than using a list to store the same set of items. Also, creating a tuple requires less time than creating a list.
The following table summarizes the differences:
Lists | Tuples |
---|---|
Defined using square brackets | Defined using rounded brackets |
✔️ Lists are mutable | ❌ Tuples are immutable |
❌ Use more memory | ✔️ Use less memory |
❌ Slower | ✔️ Faster |
Conclusions
Tuples are more memory and time efficient but cannot be modified.
Therefore, if you have data that don't need to be changed, you should use tuples. Instead, if you need to change data you are forced to use lists.
Top comments (1)
Bella spiegazione!