Possible Duplicate:
Why do we need tuples in Python (or any immutable data type)?
I’m learning Python and have background in Ruby. Not ever having tuples, I can’t imagine why I would need them or why Python leans on them so much.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The coordinates of a square on a chessboard is one example of good use of tuple. I usually use a Python dict, indexed by tuple, to implement a multidimensional array, rather than list-of-lists or the numpy or array modules:
You can’t use a mutable (like a list) as a dictionary key, so you need a tuple for this.
Occasionally you find yourself wanting to return multiple values from a function – a boolean to indicate success or failure plus a string describing the failure mode, for instance:
This isn’t a pattern to use a lot, but sometimes it gets you out of trouble. You could also use a list here; it’s only by convention that you’d normally use tuple instead.
When considering how to represent independent values that have to be passed around together, there’s almost a continuum between tuples, dicts, and classes. Consider three ways of representing that compound return:
If there’s only one place in your code where you’re doing this, the tuple is attractive for its terseness. If you’re using this pattern a lot, and passing these result pairs back and forth between different modules, you might “upgrade” to the dict, where the elements have meaningful keys. If these results become a major part of your software design, you might upgrade them again to being instances of an object class. It’s a balance between formality and ease of use.