Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cases where use of tuple is a must

Tags:

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?

like image 212
tarashish Avatar asked Jul 09 '12 16:07

tarashish


People also ask

When should you use 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.

What is use case of tuple?

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.

Where can tuple be used in real life?

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.


1 Answers

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
like image 111
Otto Allmendinger Avatar answered Oct 14 '22 16:10

Otto Allmendinger