Python variable length assignment?

The Python assignment statement can be written as follows.

a, b = 1, 2

You can also write a function with variable length arguments by writing as follows.


def func(*args):
  print(repr(args))

func(1)
#output: (1,)
func(1, 2)
#output: (1, 2)

Well, it's been a while since I started Python, so I know this much, but suddenly I wondered if I could use "*" (asterisk) in the assignment statement. It depends.

a, *b = 1, 2, 3
print((a, b))
#output: (1, [2, 3])

You can do it!

Just in case, if you check what the specifications are,

If the target list contains only one target with a single asterisk in the head, called a "starred" target: The object is iterable and is at least one less element than the number of targets in the target list. Must have. Targets before the starred target are assigned the first element of the iterable from left to right. The target at the end of the iterable is assigned to the target after the starred target. The starred target is assigned a list of the remaining elements of the iterable (the list can be empty).

It's written well.

Let's do various things.

a, *b = 1,
print((a, b))
#output: (1, [])
a, *b, c = 1, 2, 3, 4, 5
print((a, b, c))
#output: (1, [2, 3, 4], 5)
*a, = 1, 2, 3
print(a)
#output: [1, 2, 3]

However, the following is not good.

a, b, *c = 1,
# ValueError: not enough values to unpack (expected at least 2, got 1)
#c can be empty, but a,The value to be assigned to b must be specified.
*a = 1, 2, 3
# SyntaxError: starred assignment target must be in a list or tuple
# 「*Targets with "" must be in the list tuple.

Until now, it was only on the left side, but it seems that it can also be used on the right side.

d = 10, 20
a, b, c = 1, *d
print((a, b, c))
#output: (1, 10, 20)
# 「a, b, c = 1, d[0], d[1]"the same as.

Recommended Posts

Python variable length assignment?
Python underscore variable
python variable expansion, format
[Python] Multi-line string assignment
Python
New syntax for Python 3.8 [assignment formula]
[Python] Variable (definition, output, value change)
Change the length of Python csv strings
Python> link> 2D array initialization and assignment
[Python] Get the variable name with str
[Introduction to Udemy Python3 + Application] 8. Variable declaration
Combine python function arguments into one variable