6 ms·
I really adore Python's iterable- and keyword-unpacking operators (*some_iterable, **some_mapping): arr = [0, 1, 2, 3, 4] head, *body, tail = arr # he
by ddejohn 4y ago
I really adore Python's iterable- and keyword-unpacking operators (*some_iterable, **some_mapping):
arr = [0, 1, 2, 3, 4]
head, *body, tail = arr # head=0, body=[1, 2, 3], tail=4
head, *rest = arr
head, *_, tail = arr
*_, tail = arr
first, second, third, *rest = arr
foo = {"a": 1, "b": 2, "c": 3}
bar = {"b": 9, "x": -1}
{**foo, **bar} # -> {"a": 1, "b": 9, "c": 3, "x": -1}
- swyx 4y agowhy bother with the distinction between one * and two *? in javascript the … operator neatly does both
- zdragnar 4y agoTechnically, `...` acts as either the spread or the rest operator, depending on the location. I recall there was an initial impression of intimidation among people who were familiar with ES5 syntax when trying to adopt to these new features because of this. On the other hand, I'm fairly certain that having to visually disambiguate between `` and `*` and remembering which did what would have gotten a similar reaction.
- gdwatson 4y agoPython has keyword arguments to functions. In that context, a single star packs or unpacks a list of positional arguments and a double star packs or unpacks a dictionary of keyword arguments.
- gpderetta 4y agoTo complete the description, dictionaries are iterable by key only by default[1], so *dict would be ambiguous if it could splat both. [1] a misfeature, IMNSHO.
- Too 4y agoMaybe more obvious, it also works the other way around. Saving you from doing [head] + body + [tail] or keeping copies of temporary arrays manipulated with append and extend. arr = [head, *body, tail] Same with dictionaries, often very useful when you need to include **os.environ with modifications into a subprocess.
- blackbear_ 4y agoI was really disappointed when they removed support for argument unpacking. It was just so useful, especially in lambdas, for example Mdist = lambda (x1,y1),(x2,y2): abs(x1-x2)+abs(y1-y2) p1,p2=(1,2),(3,4) Mdist(p1,p2) # 4