Today we’ll learn how repetition works with lists.
Here’s the video version of the article:
You can use the * operator to repeat the elements of a list:
>>> letters = ["n", "q", "w"]
>>> letters * 3
['n', 'q', 'w', 'n', 'q', 'w', 'n', 'q', 'w']
You can also apply the repetition operator to nested lists. Here’s a list called codes:
>>> codes = [17, 5, 41]
The list codes becomes an element of a larger list. The element of the outer list, which is the inner list, is then repeated 4 times:
>>> triplets = [codes] * 4
>>> triplets
[[17, 5, 41], [17, 5, 41], [17, 5, 41], [17, 5, 41]]
Now let’s change the second element in the first inner list from 5 to 30:
triplets[0][1] = 30
Turns out the element was changed in each of the inner lists. This is because the repetition operator creates four references to the list codes:
>>> triplets
[[17, 30, 41], [17, 30, 41], [17, 30, 41], [17, 30, 41]]
This is because of shared references. If you want to learn more about them, you can read this article.