June 2017
Beginner
352 pages
8h 39m
English
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 ...
Read now
Unlock full access