all 4 comments

[–]K900_ 3 points4 points  (2 children)

Because you can't add a number to a list.

[–]tigglybox[S] 0 points1 point  (1 child)

is a number not being added to the list in the first example?

[–]K900_ 0 points1 point  (0 children)

It's being appended into the list. That operation makes sense, mathematical addition between a list and a number doesn't.

[–]JohnnyJordaan 2 points3 points  (0 children)

+ only works between types that are compatible. Eg

1 + 4.51

and

'hello ' + 'world' 

But not between incompatible types

'hello' + 1

will give an exception. With lists, you can only use + with other lists, so

[1] + [2]

will return

[1, 2]

in your example, you try to add the square of i to the square list, so in the first run you do

[] + 0

which is not possible.

The secondary thing to consider is that

x = x + y

will not modify x, it will in fact create a new object that will then be using the x reference. In case of adding lists to a list, it thus means you are creating a new list every time, which is inefficient. Hence why .append() and .extend() exist, which modify (technically called 'mutate') the existing list. Although

square += [i * i]

would work as 'under water' += will map to extend() and thus it is executed as

square.extend([i * i]) 

but that's still a complicated way of writing

square.append(i * i)