Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a tuple useful for?

Tags:

python

tuples

I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?

like image 459
Sam McAfee Avatar asked Sep 03 '08 16:09

Sam McAfee


2 Answers

  • Tuples are used whenever you want to return multiple results from a function.
  • Since they're immutable, they can be used as keys for a dictionary (lists can't).
like image 154
Chris Upchurch Avatar answered Oct 02 '22 03:10

Chris Upchurch


Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it.

a = {} a[(1,2,"bob")] = "hello!" a[("Hello","en-US")] = "Hi There!" 

I've used this feature primarily to create a dictionary with keys that are coordinates of the vertices of a mesh. However, in my particular case, the exact comparison of the floats involved worked fine which might not always be true for your purposes [in which case I'd probably convert your incoming floats to some kind of fixed-point integer]

like image 23
sphereinabox Avatar answered Oct 02 '22 01:10

sphereinabox