Unpacking actually works with any object that happens to be iterable, not just tuples list or lists. This includes strings, files, iterators,and generators.

Basic

在等号左边使用逗号 comma , 分隔与右边序列个数相同的变量来接受收他们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
In [12]: test_list = [1,2,3]
In [13]: a,b,c = test_list
In [17]: print(a,b,c)
1 2 3
In [22]: test_dict={"name":"zhangsan", "age":18}

In [23]: a, b = test_dict

In [24]: print(a,b,sep="\n")
name
age

In [27]: a, b = test_dict.items()
In [28]: a
Out[28]: ('name', 'zhangsan')

In [30]: a, b = test_dict.values()
In [31]: a
Out[31]: 'zhangsan'

Because parentheses of tuples can be omitted, multiple values can be assigned to multiple variables in one line as follows.

1
2
3
4
5
6
7
In [40]: a, b = 3,4

In [41]: a
Out[41]: 3

In [42]: b
Out[42]: 4

An error occurs if the number of variables does not match the number of elements.

1
2
3
4
5
6
In [43]: test_list = [1,2,3]
In [44]: a,b = test_list
ValueError: too many values to unpack (expected 2)

In [45]: a,b,c,d = test_list
ValueError: not enough values to unpack (expected 4, got 3)

If the number of variables is less than the number of elements, it is possible to add an asterisk * to the variable name and assign the remaining elements as a list. This will be described later.

Unpack a nested tuple and list

You can also unpack a nested tuple and list. If you want to expand the inner element, enclose the variable with () or [].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [47]: test_tuple = (0,1,(2,3,4))

In [48]: a, b, c = test_tuple

In [49]: print(a,b,c, sep="\n")
0
1
(2, 3, 4)
In [51]: a, b, (c, d, e) = test_tuple

In [52]: print(a,b,c,d,e, sep="\n")
0
1
2
3
4

Unpack using _ (underscore)

By convention, unnecessary values may be assigned to underscores _ in Python. It does not have a grammatical special meaning, but is simply assigned to a variable named _.

1
2
3
4
5
6
7
In [54]: test = [1,2,3]

In [55]: a, b, _ = test
In [58]: print(a, b, _, sep="\n")
1
2
3

Notice:variables named _ are not meant to be used, I print it here just to help you understand it in more detail.

Unpack using * (asterisk)

If the number of variables is less than the number of elements, adding an asterisk * to the variable name will assign the elements together as a list.

The elements from the beginning and the end are assigned to variables without *, and the remaining elements are assigned as a list to variables with *.

It is implemented in Python 3 and can not be used in Python 2.

Extended iterable unpacking is tailor-made for unpacking iterables ofunknown or arbitrary length.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
In [64]: test
Out[64]: [62, 83, 93, 100]

In [65]: a, b, *c = test

In [66]: print(a, b, c, sep="\n")
62
83
[93, 100]

In [67]: a, *b, c = test

In [68]: print(a, b, c, sep="\n")
62
[83, 93]
100

In [69]: *a, b, c = test

In [70]: print(a, b, c, sep="\n")
[62, 83]
93
100

Usage

Use unpacking When there are only some interesting elements in the specific positions.

  1. when it is desired to assign only the first two elements of a tuple or a list to variables, the underscore _ may be used for unnecessary parts.
1
2
3
4
5
6
7
8
9
In [73]: test
Out[73]: [62, 83, 93, 100]

In [74]: a, b, *_ = test

In [75]: print(a, b, _, sep="\n")
62
83
[93, 100]
  1. The star syntax can be especially useful wheniterating over a sequence of tuples of varying length
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]

def do_foo(x, y):
print('foo', x, y)

def do_bar(s):
print('bar', s)

for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
  1. Star unpacking can also be useful when combined with certain kinds of string processing operations, such as splitting. For example:
1
2
3
4
5
6
7
8
9
>>> line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
>>> uname, *fields, homedir, sh = line.split(':')
>>> uname
'nobody'
>>> homedir
'/var/empty'
>>> sh
'/usr/bin/false'
>>>

Notice:

  1. You can add * to only one variable.

    If there are multiple variables with *, it can not be determined how many elements are to be assigned, so SyntaxError occurs.

  2. Assigned as a list Even if there is only one element assigned to a variable with *, it is assigned as a list. If there are no extra elements, an empty list is assigned.

  3. It is also an error to use the starred expression as a lone assignment target, as in *a = range(5) This, however, is valid syntax: *a, = range(5)

  4. this proposal also applies to tuples in implicit assignment context, such as in a fortatement:

1
2
3
4
5
6
for a, *b in [(1, 2, 3), (4, 5, 6, 7)]:
print(b)

# print out
[2, 3]
[5, 6, 7]
  1. Starred expressions are only allowed as assignment targets, using them anywhere else (except for star-args in function calls, of course) is an error.

iterable

If the right-hand value is not a list, but an iterable, it has to be converted to a list before being able to do slicing; to avoid creating this temporary list, one has to resort to

1
2
3
it = iter(seq)
first = it.next()
rest = list(it)

Multiple Function Arguments

Just mention it:

python 中有两种多值参数: 参数名前增加一个 * 可以接收元组, *args 参数名前增加两个 * 可以接收字典, **kwargs

参考推荐: PEP 3132 -- Extended Iterable Unpacking Unpack a tuple / list in Python python 有趣的解包用法 Python Cookbook 3rd Edition