Course 5.1Lesson 4 of 5
A variable holds a pointer to a list, not the list itself. After b = a, both names point to the same list, so a change through one shows in the other, and is tells you whether two names are the same list. To make a real copy, use a.copy(), a[:] or list(a). A list given to a function is not copied either, so the function can change your list. A list can hold other lists, which makes a table: marks[1][2] is row 1, column 2. Loop over the rows, and then over each row.
Try the code and the simulations beside the lesson.
After this lesson you can
b = a does not copy a list,Here is a puzzle.
A variable does not hold the list itself. It holds a pointer, like a label on a box. When we write b = a, Python does not make a second list. It sticks a second label on the same box. A change through b is a change to the one box, and we see it through a too. The word is asks: "are these the same box?" a is b is True.
To make a real copy, with its own box, use a.copy(). Other ways: a[:] (a slice of everything) or list(a). Now c.append(5) changes only c, and a is c is False.
This is not a fault of Python. It is useful: a list can be big, and Python does not copy it unless you ask. But it is a famous trap.
For a string or a number, the problem does not exist, because they cannot be changed. Only a changeable thing needs this care.
The same happens when you give a list to a function. The function receives a label on your box.
A list can hold any values, and a list is a value too. So a list can hold lists. This is how we make a table, with rows and columns.
One more warning. Making a table with [[0] * 3] * 3 looks neat, but it makes three labels on one row. A change to one row shows in all three rows. Build the rows with a loop instead:
table = []
for i in range(3):
table.append([0, 0, 0])Read t[1][2] from the left: first t[1], the row [6, 2, 9], then item 2 of that row, which is 9.
A table is good for data that has two directions: students and subjects, days and cities, rows and columns of a grid for a game. For one direction only, a plain list is enough.
b = a makes a copy. It makes a second name.[[0] * 3] * 3** for a table. All the rows are one row.a.copy() of a table copies the outer list, but the inner rows are still shared. For that, make a new row for each row.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
b = a gives the list a second name. a.copy() makes a real copy.is asks whether two names are the same list.table[row][column].Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
a = [1, 2], b = a, b.append(3), what is a?a?t[2][0] mean for a table t?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.