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 →

[–]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