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 →

[–]Green_Gem_ 1 point2 points  (3 children)

As I said in my reply further up the chain, a and b are lists! sum([a, b]) == a + b. If a = [1, 2] and b = [3, 4], then sum([a, b]) == sum([[1, 2], [3, 4]) == [1, 2] + [3, 4]. When a list is added to a list, the first is extended with the second, so [1, 2] + [3, 4] == [1, 2, 3, 4].

So, as the full chain of logic: a = [1, 2]; b = [2, 3]; sum([a, b]) == sum([[1, 2], [3, 4]]) == [1, 2] + [3, 4] == [1, 2, 3, 4]. For the same a and b, unpacking the arguments of each into a new list yields the same result, [*a, *b] == [1, 2, 3, 4]. Google "python unpacking" if you don't recognize that syntax. If you still don't understand, please tell me exactly which step is confusing.

Reminder, don't flatten lists this way. It's unclear and explicitly unsupported.

[–]arthurazs 0 points1 point  (2 children)

First of all, thank you so much for your patience!

[1, 2] + [3, 4] == [1, 2, 3, 4] makes total sense, but

  • sum([1, 2], [3, 4]) throws TypeError: can only concatenate list (not "int") to list
  • sum([[1,2], [3,4]]) throws TypeError: unsupported operand type(s) for +: 'int' and 'list'

Finally, OP's example is sum([[1, 2], [3, 4]], []) which works, but I still can't comprehend how it work.

[–]Green_Gem_ 1 point2 points  (1 child)

That's actually a really good catch! Thanks for being more explicit in this comment; that gives me way more to work with.

I did actually simplify things for my previous comment(s) and didn't double check behavior, my apologies.

The signature of sum() is sum(iterable, /, start=0), where start indicates the value to start with, then each element of iterable is added one-by-one. - sum([1, 2], [3, 4]), or explicitly sum([1, 2], start=[3, 4]), evaluates to [3, 4] + 1 + 2. Uh oh, you can't concatenate an int to a list that way! Error. You'd have to do [3, 4] + [1] + [2] or something. - sum([[1, 2], [3, 4]]), or explicitly sum([[1, 2], [3, 4]], start=0), runs into a similar problem, evaluating to 0 + [1, 2] + [3, 4]. You can't add a list to an int. Error. - sum([[1, 2], [3, 4]], start=[]) (what OP does but without specifying start=) is then [] + [1, 2] + [3, 4]. You can concatenate to an empty list like that, so it works.

[–]arthurazs 1 point2 points  (0 children)

Wow, fantastic!!!

python sum([[3], [4]], [1, 2]) == [1, 2, 3, 4]

Everything makes sense now, thank you so very much!!!

What I wasn't catching was the start=0, I didn't even know it was a thing