Tuple unpacking

Unpacking a tuple means giving a different name to each element of the tuple.

Tuple unpacking is useful because many functions in Python, such as the zip() function described in the previous "Building lists incrementally" section, return tuples. With tuple unpacking, you can easily get at the individual items in these tuples.

To unpack a tuple, just assign multiple names on a single line. Put the names you want to unpack into on the left side of the assignment statement and put the tuple on the right side. You need one name for each item in the tuple.

The following example unpacks a tuple consisting of three lists:

>>> x = [('rock crushes', 'scissors'), ('paper covers', 'rock'),

If you don't have the same number of names as tuple items, you get a vaiueError, as shown here:

Traceback (most recent call last): File "<stdin>", line 1, in <module> VaiueError: too many values to unpack

Tip You can actually unpack any sequence object in this way. The following example unpacks a string:

>>>

x = '

string'

>>>

a, b,

c,

d, e,

f = x

>>>

a

's'

>>>

print

a,

b, c,

d, e, f

s t

r i n

g

However, unpacking is most commonly used with tuples because there are better ways to get elements out of strings and lists.

Was this article helpful?

0 0

Responses

  • diamond fairbairn
    How to untuple a tuple python unpacking?
    5 years ago
  • Dennis
    How to unpack tuple python?
    5 years ago

Post a comment