Packing and Unpacking Tuples

suggest change

Tuples in Python are values separated by commas. Enclosing parentheses for inputting tuples are optional, so the two assignments

a = 1, 2, 3   # a is the tuple (1, 2, 3)

and

a = (1, 2, 3) # a is the tuple (1, 2, 3)

are equivalent. The assignment a = 1, 2, 3 is also called packing because it packs values together in a tuple.

Note that a one-value tuple is also a tuple. To tell Python that a variable is a tuple and not a single value you can use a trailing comma

a = 1  # a is the value 1
a = 1, # a is the tuple (1,)

A comma is needed also if you use parentheses

a = (1,) # a is the tuple (1,)
a = (1)  # a is the value 1 and not a tuple

To unpack values from a tuple and do multiple assignments use

# unpacking AKA multiple assignment
x, y, z = (1, 2, 3) 
# x == 1
# y == 2
# z == 3

The symbol \_ can be used as a disposable variable name if one only needs some elements of a tuple, acting as a placeholder:

a = 1, 2, 3, 4
_, x, y, _ = a
# x == 2
# y == 3

Single element tuples:

x, = 1,  # x is the value 1
x  = 1,  # x is the tuple (1,)

In Python 3 a target variable with a \* prefix can be used as a catch-all variable (see http://stackoverflow.com/documentation/python/809/compatibility-between-python-3-and-python-2/2845/unpacking-iterables ):

first, *more, last = (1, 2, 3, 4, 5)
# first == 1
# more == [2, 3, 4]
# last == 5

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Tuple:
* Tuple
* Tuple
* Packing and Unpacking Tuples

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve