Repeating lists

As for strings and tuples, lists support repetition using the multiplication operator. It's simple enough to use:

>>> c = [21, 37]
>>> d = c * 4
>>> d
[21, 37, 21, 37, 21, 37, 21, 37]

Although it's rarely spotted in the wild in this form. It's most often useful for initializing a list of size known in advance to a constant value, such as zero:

>>> [0] * 9
[0, 0, 0, 0, 0, 0, 0, 0, 0]

Be aware, though, that in the case of mutable elements the same trap for the unwary lurks here, since repetition will repeat the reference to each element, without copying the value. Let's demonstrate using nested lists as our mutable elements again:

>>> s = [ [-1, +1] ] * 5
>>> s
[[-1, 1], [-1, 1], [-1, 1], [-1, 1], [-1, 1]]

Repetition is shallow, as illustrated in the following diagram:

Figure 5.18: Repitition is shallow.

If we now modify the third element of the outer list:

>>> s[2].append(7)

We see the change through all five references which comprise the outer list elements:

>>> s
[[-1, 1, 7], [-1, 1, 7], [-1, 1, 7], [-1, 1, 7], [-1, 1, 7]]

Mutating the repeated contents of a list. Any change to the object is reflected in every index of the outer list:

Figure 5.19: Repetition is mutation.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset