An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
List vs Tuple - When To Use Each?
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.
Original Link: https://dev.to/cscarpitta/list-vs-tuple-when-to-use-each-4e99
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To