When you unpack and pick up an 8x mirror, it's fast, accurate and cruel

Tuple unpacking

Tuples are immutable lists, which are retrieved by index, and tuples are also:

tuple_test = (1, 2, 3)
a = tuple_test[0]
b = tuple_test[1]
c = tuple_test[2]

But Python is a famous line of code to solve the problem. Tuple unpacking is one of the essence technologies:

a, b, c = tuple_test
print("%s %s %s" % tuple_test)

Unpacking tuples one by one is called unpacking tuples. There is a requirement for unpacking. The number of elements in the tuple must be consistent with the number of neutral positions that accept these elements, otherwise an error will be reported:

tuple_test = (1, 2, 3)
a, b = tuple_test  # ValueError: too many values to unpack (expected 2)

_ placeholder

Use_ Placeholders can solve this problem:

tuple_test = (1, 2, 3)
a, b, _ = tuple_test

In this way, only part of the data is obtained, which is particularly useful when taking the return value of the function, such as:

import os

_, filename = os.path.split("/home/dongfanger/.ssh/idrsa.pub")
print(filename)  # "idrsa.pub"


When there are too many return values_ Placeholders are cumbersome to write. You can use * to deal with the remaining elements:

>>> a, b, *rest = range(5)
>>> a, b, *rest
(0, 1, [2, 3, 4])

Note that rest is a list. If there are not enough elements, an empty list will be returned:

>>> a, b, *rest = range(2)
>>> a, b, *rest
(0, 1, [])

*Prefix variables can be placed anywhere, for example, in the middle:

>>> a, *body, c, d = range(5)
>>> a, body, c, d
(0, [1, 2], 3, 4)

Put in front:

>>> *head, b, c, d = range(5)
>>> head, b, c, d
([0, 1], 2, 3, 4)

It's wonderful.

*Another function is to disassemble tuples as function parameters:

>>> divmod(20, 8)
(2, 4)
>>> t = (20, 8)
>>> divmod(*t)
(2, 4)

Classic writing * args is this truth.

Unpacking nested tuples

Nested tuples refer to tuples in tuples, such as (1, 2, 3, (4, 5)). For nested tuples, you may want to disassemble them twice:

tuple_nest_test = (1, 2, 3, (4, 5))
a, b, c, d = tuple_nest_test
x, y = d
print(a, b, c, x, y)

In fact, it can be achieved in one step:

tuple_nest_test = (1, 2, 3, (4, 5))
a, b, c, (x, y) = tuple_nest_test
print(a, b, c, x, y)

Exchange the values of two variables

Tuple unpacking provides syntax sugar, which is a general way to exchange the values of two variables:

temp = a
a = b
b = temp

You can switch to elegant writing:

b, a = a, b

named tuple

Tuples are much like database table records, except that there are no table names and field names Namedtuple named tuple compensates for this shortcoming. It is a factory function that can be used to build a tuple with field name and a named class, such as:

import collections

# definition
Card = collections.namedtuple("Card", ["rank", "suit"])
# initialization
card_test = Card("J", "hearts")
# use
print(card_test.rank)  # J
print(card_test[1])  # hearts

Card is the table name and has two table fields, rank and suit.

Defining a named tuple requires two parameters. The first parameter is the class name and the second parameter is the field name. It can be either an iteratable object (such as a list and tuple) or a space spaced string:

Card = collections.namedtuple("Card", ("rank", "suit"))
Card = collections.namedtuple("Card", "rank suit")

During initialization, the constructor is passed in the form of a string of parameters:

card_test = Card("J", "hearts")

Both can pass Operator, you can also use the index to get the value:


This tuple with name is of great help to the debugger.

List and tuple

Tuples are immutable lists. They are like twins. They look similar but have different internal personalities:

The Yellow list is unique, the red tuple is unique, and there is an S__ getnewargs__ () method! It is clear from the table that tuples support all methods of the list except those related to adding or removing elements.

The list can also be disassembled

Since lists and tuples are twin brothers, they must also have common skills:

list_test = [1, 2, 3]
a, b, c = list_test
>>> divmod(20, 8)
(2, 4)
>>> t = [20, 8]  # Change to list
>>> divmod(*t)
(2, 4)

List unpacking is also ok.


This paper introduces Python magic operation tuple unpacking, with the help of_ Placeholder and * prefix can take more flexible values, and named tuples are rarely used in practice, but there are some source codes. Finally, the paper compares the differences between list and tuple. List can also unpack. Lists, tuples, and STRs all have a common operation: slicing.

reference material:

Fluent Python

Posted by sdizier on Mon, 18 Apr 2022 03:28:18 +0930