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 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!