[Tutor] unpacking
Daniel Ehrenberg
littledanehren at yahoo.com
Sun Jan 11 21:55:25 EST 2004
Christopher Spears wrote:
> What is unpacking?
>
> -Chris
Tuple packing and unpacking is a simple but powerful
mechanism that python uses for multiple assignment,
creation of tuples, and seperation of the elements of
a list or tuple. You can't really understand unpacking
until you understand packing. To pack a tuple, simply
place commas between different things. This will
automatically form a tuple. The comma has somewhat low
precidence, so you will sometimes need to put parens
around it. Tuples can be treated like lists for the
most part, except they are immutable. Here are some
examples using tuples:
>>> 1, 2
(1, 2)
>>> x = 1, 2
>>> x
(1, 2)
>>> x = (1, 2, 3, 4), 5, 6, 7
>>> x
((1, 2, 3, 4), 5, 6, 7)
>>> x[1]
5
>>> x[0]
(1, 2, 3, 4)
>>> x[0][2]
3
Taking a tuple apart is just as easy as making it.
Although you could go through the process like the
following:
>>> x = 1, 2
>>> x0 = x[0]
>>> x1 = x[1]
it is much easier to do this:
>>> x = 1, 2
>>> x0, x1 = x
When things are seperated by commas on the left side
of the =, Python interprets it that you want to take
each element of the tuple and store it in those
variables. This is called unpacking.
When you use multiple assignment, as in the following:
>>> x, y = 1, 2
>>> x
1
>>> y
2
Python is actually constructing 1, 2 into a tuple and
then unpacking it onto x and y.
Daniel Ehrenberg
__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus
More information about the Tutor
mailing list