That tricky asterisk

If you repeat (*) a list, you get a list with multiple copies of its elements. But if you repeat (*) a list containing a list, you get multiple shallow copies of the contained list. The following examples demonstrate both repeating a list and repeating a list that contains a list:

• Repeating a list containing a list:

In the preceding examples, if you change mylist, the value of y changes because y contains references to mylist. But the value of x doesn't change because x only contains copies of the elements of mylist. Here's what happens:

We change the first element of mylist:

Here's the result:

• y reflects the new version of mylist:

• [['two', 'blind', 'mice'], ['two', 'blind', 'mice']]

Was this article helpful?

0 0

Post a comment