C5W1 Assignment 2: Model () adding lists

It’s funny sometimes how the same problem seems to crop up in multiple places at the same time. Here’s another parallel thread with a slightly different variation on this same problem.

The point in all of this is that you have to be really careful to understand the meaning of the syntax. If A is a list, then these two statements do not have the same effect:

B = [42] + A
C = [42] + [A]

Try it and see what happens. If len(A) is 4 a priori, then what do you think len(C) is? If you guessed 5, you’re in for a big surprise.

Here’s a worked example. Run the following code and watch what happens:

A = [1, 2, 3, 4]
B = [42] + A
C = [42] + [A]

You can insert a new cell to run the code by doing ‘Insert → Cell Below’.

If you’re new to python then you have to be careful: you can’t just assume you know what something does. You have to try it and examine the results. When things aren’t working, it probably means you’re misusing some piece of the syntax. The more useful approach is to stop and actually look at the results to understand what the meaning actually is, rather than just randomly trying things and getting frustrated.