Hacker News new | ask | show | jobs
by kdmccormick 857 days ago
I feel the same way about list concatenation! I'm sure some will disagree, but IMO now that Python has "splatting" in list expressions:

    xs = [2, 3, 4]
    ys = [1, *xs, 5]
the old way feels backwards:

    xs = [2, 3, 4]
    ys = [1] + xs + [5]
3 comments

Agreed. This is one of those cases where "there should be one -- and preferably only one -- obvious way to do it" ought to apply. Of course, there are practical backwards compatibility reasons to keep + working as it does.

But overloading + for lists in general is a footgun anyway, especially in a dynamically typed language where the actual behavior is determined at runtime. And Python went one step further and also defined += for lists, and did it in a way that is even worse, because this:

   xs += [1]
does not behave the same as this:

   xs = xs + [1]
(the latter creates a new list and assigns the reference to it to xs; the former mutates the list in-place without changing the value of the variable)

Then on top of that you have scoping issues, too, because += is considered an assignment operator, and thus variable on the left side of it is considered a local unless you have a "global" declaration. So if you do this:

   xs = []
   def foo(): xs += [1]
it doesn't work as expected, because xs inside foo is a new local that shadows the global xs - and it fails at runtime because local xs is not initialized. You have to either do "global xs", or else write xs.append(1) in this context. At which point you might as well just use .append() everywhere, since at least it works consistently.

All in all, it's a good illustration of what happens when people get too "clever" with syntactic sugar when designing a PL.

I prefer the js:

  ys = [1, ...xs, 5]
It is more visually indicative of a 'spread' of values.
It's definitely more visually intuitive for someone new to the language. But Python has used asterisk for unpacking lists in other places, so the first time I saw it done for array spreading it made perfect sense.
i think this was probably doable with some form of tuple magic in one form or another, but i agree. now if only they would add the spread operators to the ‘operator’ package… (don’t ask why— the heart wants what it wants…)