Implementation method of python tuple unpacking

  • 2021-09-11 20:53:18
  • OfStack

1. Description

Putting out tuple 11 correspondingly is called tuple unpacking. Unpacking has a requirement that the number of elements in the tuple must be equal to the number of nulls 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)

2. Examples

_ Placeholder

Use the _ placeholder to solve this problem:


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

In this way, only part of the data is obtained, which is especially 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"

Extension of basic knowledge points:

Tuples?

Characteristics of tuples:

Equivalent to an immutable list;

Can be used for records without field names.

The tuple in pythn is equivalent to the array in C language, which is immutable, but can also accommodate different types of elements, and is also a kind of container.


>>> t = (1,2,'a','b','c')
>>> t
(1, 2, 'a', 'b', 'c')
>>> type(t)
<class 'tuple'>

There are two main methods for tuples:

index (): Gets the subscript of the specified element within the tuple count (): Counts the number of occurrences of the specified element within the tuple

The definition and structure of a tuple is similar to a list, but it is relatively simple to use, and the elements of a tuple are contained with '()'.

The above is the python tuple unpacking implementation method details, more about python tuple unpacking how to achieve information please pay attention to other related articles on this site!


Related articles: