October 25, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Learn to Program using Python: Unpacking Tuples

  • June 8, 2004
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »


Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.  The ultimate objective is to progress to JPython, forming the link between Python and Java.

Viewing tip

You may find it useful to open another copy of this lesson in a separate browser window.  That will make it easier for you to scroll back and forth among the different listings, without losing your place, while you are reading about them.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along. Learn to Program using Python: Lesson 1, Getting Started , provides an overall description of this online programming course.

Introduction

This is another lesson in a series of lessons designed to teach you about tuples.

Previous lessons (see Learn to Program using Python: Nested Tuples ) have illustrated

  • How to create (pack) a tuple.
  • How to access a tuple item using indexing.
  • How to slice a tuple.
  • How to nest tuples.
  • How to create empty tuples.
  • How to create single-item tuples.
Preview

This lesson will teach you about unpacking tuples.

What Is a Tuple?

A tuple is an immutable ordered list of objects.  It can contain references to any type of object.  See Learn to Program Using Python: Empty and Single-Item Tuples for a more detailed description.

Sample Program

Unpacking a tuple

Listing 1 shows the beginning of a Python script that:

  • Creates (packs) two simple tuples.
  • Creates (packs) a third tuple by concatenating the first two tuples.
  • Displays the third tuple.
  • Unpacks the third tuple, assigning each item of the tuple into a separate variable.
  • Displays each of the variables.
  • Creates and displays a mutable list object containing five strings.
  • Unpacks the tuple created earlier assigning the four items from the tuple into the first four items in the list.
  • Displays the list.
# File Tuple04.py
#-------------------------------
# Create a pair of tuples
t1 = 1,2
t2 = "A","B"

# Concatenate and print them
t3 = t1 + t2
print t3

Listing 1

(Note that some of the text in the listings was highlighted using boldface for emphasis.)

The remaining parts of this program are shown as code fragments in subsequent listings.  A listing of the entire program is shown in Listing 7 near the end of the lesson.

Tuples can be concatenated

As shown in Listing 1, tuples support the concatenation (+) operator.  You can concatenate two or more tuples to produce a new tuple.  This program creates two simple tuples, and then concatenates them to create a third tuple.

The output

Listing 2 shows the output produced by the code in Listing 1.  By now, the creation and display of simple tuples should be very familiar to you based on earlier lessons (see Learn to Program using Python: Tuples, Index and Slice ) .  Therefore, I won't discuss this part of the program further.
 

(1, 2, 'A', 'B')

Listing 2

Now for something strange...

The code in Listing 3 is not quite so straightforward.  In fact, it looks rather strange if you come from a conventional C, C++, or Java programming background.
 

# Unpack the tuple and print
# individual elements
w,x,y,z = t3
print w
print x
print y
print z

Listing 3

What do Lutz and Ascher have to say?

Here is what Lutz and Ascher, authors of Learning Python, from O'Reilly, have to say about this syntax.  They refer to this as Tuple assignment (positional).

"When you use tuples or lists on the left side of the =, Python pairs objects on the right side with targets on the left and assigns them from left to right."

What does Guido van Rossom have to say?

The Python Tutorial by Guido van Rossum refers to the boldface statement in Listing 3 as tuple unpacking.

Guido van Rossom points out

"Tuple unpacking requires that the list of variables on the left has the same number of elements as the length of the tuple."

Otherwise, an error occurs

If you try to run a script that doesn't meet these criteria, you will get the following error:

ValueError: unpack tuple of wrong size

What is tuple packing?

Interestingly, Guido van Rossum refers to the creation of a tuple (see the three lines of code used to create tuples in Listing 1) as tuple packing.

Some more output

Listing 4 shows the output produced by the code in Listing 3.
 

1
2
A
B

Listing 4

If you compare this output with the original tuple in Listing 1, or with the previous output in Listing 2, you will see that each of the individual items in the tuple (in left-to-right order) were assigned respectively to the variables named w, x, y, and z.

Thus, the lines of output produced by printing these four variables in Listing 4 match the items in the original tuple that was created in Listing 1 and displayed in Listing 2.

A mutable list

Just to make things a little more interesting, I decided to combine the use of a tuple (an immutable list) and a regular mutable list in this program.

Listing 5 contains the code to create a mutable list populated with five string characters.
 

# Create and print a list
L1 = ["a","b","c","d","e"]

print L1

# Unpack tuple into the list
# and print it
L1[0],L1[1],L1[2],L1[3] = t3
print L1

Listing 5

Then the list is displayed, as shown in Listing 6.  The first line of output in Listing 6 shows the contents of the list just after it is created and populated.
 

['a', 'b', 'c', 'd', 'e']
[1, 2, 'A', 'B', 'e']

Listing 6

Unpack the tuple into the mutable list

Then, as shown in Listing 5 the tuple from above is unpacked with the individual items being assigned to the first four items in the list (remember, a list is mutable, so the values of its items can be changed).

Look at the list again

Then the contents of the list are displayed again.  As you can see from Listing 6, the first four items in the list were replaced by the four items from the tuple.  The fifth item in the list was not modified.

The real difference...

So, what is the real difference between a tuple (an immutable list) and an ordinary mutable list as used in this sample program?

An experiment

Try the following experiment.  There is a line in the program (shown in Listing 7 near the end of this lesson) that reads as follows:

L1 = ["a","b","c","d","e"]

Modify the program, changing this line so that it reads as follows:

L1 = ("a","b","c","d","e")

Converting a list into a tuple

I hope you recognize that by replacing the square brackets with parentheses, you have changed L1 from an ordinary mutable list to a tuple (an immutable list).

Execute the script

Now execute the script.  Your output should look something like that shown in Listing 8.
 

(1, 2, 'A', 'B')
1
2
A
B
('a', 'b', 'c', 'd', 'e')
Traceback (innermost last):
  File "junk.py", line 28, in ?
    L1[0],L1[1],L1[2],L1[3] = t3
TypeError: object doesn't support
item assignment

Listing 8

Everything should work well until the attempt is made to unpack the tuple named t3 and to assign the items from that tuple into the individual items of the new tuple named L1.

Game over

The items in a tuple are immutable, meaning that they cannot be changed.  Therefore, the program crashes at this point with the following error message:

TypeError: object doesn't support
item assignment
 

Summary

Among other things, this lesson has illustrated:
  • Tuple concatenation.
  • Tuple unpacking (or tuple assignment).
  • Tuple packing.

What's Next?

Upcoming lessons will show you how to:
  • Index inside of nested tuples.
  • Slice nested tuples.
  • Modify values stored in an object referred to by an item in a tuple.

Review

1.  True of false?  Tuples support the use of the concatenation operator.

Ans:  True.

2.  Write a Python script that illustrates unpacking a tuple.

Ans:  See Listing 9.
 

# File Tuple16.py
# Rev 7/31/00
# Copyright 2000, R. G. Baldwin
# Illustrates unpacking a tuple
#
#-------------------------------
w,x,y,z = (1,2,3,4)
print w
print x
print y
print z

Listing 9

3.  True or false?  The following is valid Python code.

v,w,x,y,z = t

Ans:  True.  The above is valid Python code if t is a tuple, a list, or a string whose length matches the number of variables on the left of the assignment operator.

4.  Write a Python script that illustrates tuple packing.

Ans:  See Listing 10.
 

# File Tuple17.py
# Rev 7/31/00
# Copyright 2000, R. G. Baldwin
# Illustrates packing a tuple
#
#-------------------------------
t1 = 1,2,3,4
print t1

Listing 10

5.  Write a Python script that illustrates tuple concatenation.

Ans:  See Listing 11.
 

# File Tuple18.py
# Rev 7/31/00
# Copyright 2000, R. G. Baldwin
# Illustrates concatenating 
#  tuples
#-------------------------------
t1 = (1,2) + (3,4)
print t1

Listing 11

6.  Write a Python script that illustrates how to unpack a tuple into a list.

Ans:  See Listing 12.
 

# File Tuple19.py
# Rev 7/31/00
# Copyright 2000, R. G. Baldwin
# Illustrates unpacking a tuple 
#  into a list
#-------------------------------
L1 =["a","b","c"]
L1[0],L1[1],L1[2] = (0,1,2)
print L1

Listing 12

Listing of Sample Program

A complete listing of the program is shown in Listing 7.
 
# File Tuple04.py
# Rev 7/31/00
# Copyright 2000, R. G. Baldwin
# Illustrates unpacking a tuple
#
#-------------------------------
# Create a pair of tuples
t1 = 1,2
t2 = "A","B"

# Concatenate and print them
t3 = t1 + t2
print t3

# Unpack the tuple and print
# individual elements
w,x,y,z = t3
print w
print x
print y
print z

# Create and print a list
L1 = ["a","b","c","d","e"]
print L1

# Unpack tuple into the list
# and print it
L1[0],L1[1],L1[2],L1[3] = t3
print L1

Listing 7



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel