Skip to content

Computer Science · Ch 9 — Lists

Repetition

9.2.2

Repetition

Python can replicate a list using the repetition operator, written with the symbol *. Multiplying a list by an integer n produces a new list in which the original elements are repeated n times over, in order.

>>> cheer = ['Hip']
# elements of cheer repeated 3 times
>>> cheer * 3
['Hip', 'Hip', 'Hip']

Repetition is not limited to single-element lists — every element of the list takes part in each repetition:

>>> pair = [0, 1]
>>> pair * 4
[0, 1, 0, 1, 0, 1, 0, 1]

As with concatenation, the * operation only produces the repeated list; the original list is not modified. Assign the result to a variable if you want to keep it:

>>> row = ['-'] * 5
>>> row …