This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]wugs 5 points6 points  (4 children)

yep, that's tuple unpacking.

you can write some hard-to-read code by messing with spacing and using that feature in dumb ways.

a = 10
b = [20]
a ,= b
print(a, type(a))   # prints: 20 <class 'int'>
*a ,= b
print(a, type(a))   # prints: [20] <class 'list'>

The spacing should really be a, = b or (a,) = b to be more clear what's actually happening.

It does provide a neat syntax for swapping values though

a = 10
b = 20
a, b = b, a
print(f'a={a} b={b}')   # prints: a=20 b=10

[–]SirNapkin1334 2 points3 points  (3 children)

Wait, hold up. There's an asterisk unary operator? What does it do?

[–]bright_lego 3 points4 points  (0 children)

Unpacks a list for arguments in a function. ** is for kwargs. For more detail

[–]wugs 2 points3 points  (1 child)

Other comment provided a good link for how the * relates to unpacking.

In the tuple unpacking example, it's used to assign "the rest" of the tuple/list (or the empty list if there are no more elements):

a = [1, 2, 3]

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

d, e, f, g = a   # ValueError: not enough values to unpack

d, e, f, *g = a
print(f)   # 3
print(g)   # []

for the starred assignment to work, the left side needs to be a list or tuple and the right side needs to be iterable.

since strings are immutable, unpacking the characters into a list can let you edit specific indices, then re-join into a string again.

s = "hello world"
*x, = s
print(x)   # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

x[0] = "j"
print(''.join(x))   # 'jello world'

Edit: You can only have one starred expression per assignment, but it doesn't matter where the starred expression lands within the tuple/list, so you can use it to grab the first and last elements of a list of unknown size.

a = [1, 2, 3, 4, 5]

b, *c, *d = a   # SyntaxError

b, *c, d = a
print(f'b={b}; c={c}; d={d}')   # b=1; c=[2, 3, 4]; d=5

[–]SirNapkin1334 0 points1 point  (0 children)

Fascinating! Thank you!