Hướng dẫn python unpack list

Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise.

Introduction to the list unpacking

The following example defines a list of strings:

colors = ['red', 'blue', 'green']

Code language: Python (python)

To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:

red = colors[0] blue = colors[1] green = colors[2]

Code language: Python (python)

However, Python provides a better way to do this. It’s called sequence unpacking.

Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example:

red, blue, green = colors

Code language: Python (python)

This statement assigns the first, second, and third elements of the colors list to the red, blue, and green variables.

In this example, the number of variables on the left side is the same as the number of elements in the list on the right side.

If you use a fewer number of variables on the left side, you’ll get an error. For example:

colors = ['red', 'blue', 'green'] red, blue = colors

Code language: Python (python)

Error:

ValueError: too many values to unpack (expected 2)

Code language: Python (python)

In this case, Python could not unpack three elements to two variables.

Unpacking and packing

If you want to unpack the first few elements of a list and don’t care about the other elements, you can:

  • First, unpack the needed elements to variables.
  • Second, pack the leftover elements into a new list and assign it to another variable.

By putting the asterisk (*) in front of a variable name, you’ll pack the leftover elements into a list and assign them to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print(red) print(blue) print(other)

Code language: Python (python)

Output:

red blue ['green']

Code language: Python (python)

This example assigns the first and second elements of the colors list to the red and green variables. And it assigns the last element of the list to the other variable.

Here’s another example:

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print(cyan) print(magenta) print(other)

Code language: Python (python)

Output:

cyan magenta ['yellow', 'black']

Code language: Python (python)

This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the other variable.

Summary

  • Unpacking assigns elements of the list to multiple variables.
  • Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

Did you find this tutorial helpful ?

Unpack trong python

Link bài viết gốc ở blog của mình: chienkira.github.io/blog/thủ thuật unpack trong python


Ký tự * ngoài là toán tử multiplication (phép nhân) và string replication ra, trong Python nó còn có một tác dụng khác khá xịn xò - unpack (một số người còn gọi là splat).

Ký hiệu *

Unpack chỉ có thể áp dụng lên một object loại iterable, để áp dụng việc cần làm là đặt ký hiệu * lên liền ngay trước object đó.

Ví dụ:
Dùng trực tiếp với biến: *list_variable
Dùng với biểu thức: *[i*2 for i in some_array]

Phép unpack với ký hiệu * sẽ sinh ra "các phần tử", được tách ra từ iterable object ban đầu.

Ví dụ như

  • Nếu áp dụng lên một object kiểu list, ta sẽ nhận được các phần tử có trong list đó.
  • Nếu áp dụng lên một object kiểu dictionary, ta sẽ nhận được các keys (chỉ key thôi, không có value) có trong dictionary đó.

Cùng xem qua đoạn code ví dụ sau để hình dung rõ hơn công dụng của unpack.

# Method test nhận vào 3 params
def test(a, b, c):
    print("a =", a)
    print("b =", b)
    print("c =", c)

# object này có 3 phần tử
list = [1, 2, 3]

test(list)
# Sẽ bị lỗi TypeError: test() missing 2 required positional arguments: 'b' and 'c'

test(*list)
# a = 1
# b = 2
# c = 3

Unpack đã giúp tách độc lập các phần từ có trong object list ra, do đó method test nhận vào được đúng 3 params a, b và c tương ứng với 3 phần tử trong object list.

Đến đây thì nếu liên tưởng chút, ta sẽ thấy cách viết quen thuộc sau hiện lên ở trong đầu.

def my_method(*args):
    #do something

Vâng chính là nó rồi đó ạ, *args quen thuộc ở đây bản chất là một trick sử dụng phép unpack. Unpack biến args tương đương với chuỗi các param truyền vào method. Vì thế mà trong method khi truy cập biến args, ta nhận được list chứa toàn bộ các params. Mình hay gọi cái này là phép nghịch đảo của unpack cho dễ hiểu.

Nhắc đến *args rồi thì lại phải nhắc đến họ hàng của nó là **kwargs

) Vậy thì ta chuyển sang mục tiếp theo Ký hiệu ** thôi!

Ký hiệu **

Unpack khi sử dụng ký hiệu ** có hiệu quả khác với khi sử dụng ký hiệu * ở chỗ, nó chuyên tách object kiểu dictionary thành các cặp key-value độc lập.

Nó giúp việc truyền một dict vào một method mà chỉ nhận keyword params dễ dàng hơn rất nhiều.

Đoạn code demo ví dụ sau sẽ dễ hiểu hơn mọi giải thích dài dòng

# Method test nhận vào 3 keyword params
def test(a=a, b=b, c=c):
    print("a =", a)
    print("b =", b)
    print("c =", c)

# dict này có 3 key, thứ tự có thể không cần giống thứ tự keyword trong method test
dict = {"a": 11, "c": 22, "b": 33}

test(dict)
# Sẽ bị lỗi TypeError: test() missing 2 required positional arguments: 'b' and 'c'

test(**dict)
# a = 11
# b = 22
# c = 33

Unpack trong các ngôn ngữ khác

Javascript ES 6 cũng đã hỗ trợ phép unpack nhưng với tên gọi khác là spread, và sử dụng ký hiệu ....

const numbers = [5, 6, 8, 9, 11, 999]
Math.max(...numbers)

Còn trong ruby thì gọi là phép splat, về mặt ký hiệu và cách dùng nó giống như python.

people = ["Rudy", "Sarah", "Thomas"]
say *people

Sử dụng lâu rồi nhưng không hiểu bản chất bên dưới của nhiều đoạn code là phép unpack này, thật là xấu hổ quá. Bài này chủ yếu mang tính sắp xếp lại kiến thức của bản thân. Nếu bạn nào trót vào đọc và thấy chả có khỉ gì thì rất xin lỗi ạ!


Link bài viết gốc ở blog của mình: chienkira.github.io/blog/thủ thuật unpack trong python