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.
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.
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:
board = {}
board[ 3, 6 ] = "black queen"
board[ 0, 0 ] = "white king"
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:
if trickyOperationSucceeds():
return True,"Success!"
return False,"The tricky thing failed!"
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:
(False, "The tricky thing failed!")
{ "status": False, "message": "The tricky thing failed!" }
ResultObject( status=False, message="The tricky thing failed!" )
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.
A tuple is simply an immutable sequence, so you can't assign to the individual items of a tuple. One example might be a set of x-y coordinates like (5, 10), (-3, 20), (0, 0)
. If you needed to update some of these coordinates you could recreate the tuples like
coord = (5, 10)
# Our thing moves
newCoord = (coord[0] + dx, coord[1] + dy)
A tuple is supposed to be used for heterogenous data; it is the Python equivalent of C's struct
or Pascal's record
. Appending elements to such a type doesn't make sense, so there is no need for it to be mutable. Contrast with a list, which is for homogenous data:
people = [(u'Bob', 24), (u'Sally', 27)]
polygon = [(1, 1), (2, 3), (0, 0)]