Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Repetition
4.2.2
Repetition
Where concatenation joins different lists, repetition replicates one list. Python allows us to replicate the contents of a list using the repetition operator, depicted by the symbol *. Writing a list on one side of * and an integer on the other produces a list in which the original elements appear that many times over, one copy after another.
>>> list1 = ['Hello']
>>> list1 * 4 # elements of list1 repeated 4 times
['Hello', 'Hello', 'Hello', 'Hello']
The single-element list ['Hello'] multiplied by 4 yields a four-element list — the contents repeated, in order, four times.
A few observations that follow directly from how the operator behaves:
- It is the same
*symbol as multiplication, but with a list operand it means "repeat", not "multiply arithmetically". Python chooses the meaning from the operand types, exactly as it does for+with lists. - The whole contents are replicated in sequence. If the list had several elements, each repetition would reproduce the entire run of elements before starting the next copy — the order inside the list is preserved in every copy.
- The result is a new list. Like concatenation, repetition produces a fresh value; the original
list1still holds just['Hello']afterwards. To keep the repeated list, assign it to a variable, for examplelist2 = list1 * 4. …