In Python, the only difference between a list and a tuple that I know of is "lists are mutable but tuples are not". But as far as I believe, it depends on whether the coder wants to risk mutability or not.
So I was wondering whether there are any cases where the use of a tuple over a list is a must. Things that can not be done with a list but can be done with a tuple?
Tuples are more memory efficient than the lists. When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered. If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists.
Different Use Cases tuple Using a tuple can allow the programed and the interpreter a hint that the data should not be changed but in case of lists, we all know that it immutable in nature. So it gives an idea that it can be modified. Tuples are widely used as a dictionary without a key to store data.
You can use a Tuple to store the latitude and longitude of your home, because a tuple always has a predefined number of elements (in this specific example, two). The same Tuple type can be used to store the coordinates of other locations.
You can use tuples as keys in dictionaries and insert tuples into sets:
>>> {}[tuple()] = 1
>>> {}[list()] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Which is basically a result of a tuple
being hashable while a list
isn't:
>>> hash(list())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple())
3527539
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With