You can repeat or replicate a list multiple times using the *
operator. This operation creates a new list that contains multiple copies of the original list’s elements in sequence. List repetition is helpful when you want to create a longer list by repeating an existing sequence without manually duplicating it.
The syntax for list repetition is simple: new_list = original_list * n
, where n
is the number of times you want to repeat the list.
# Example of list repetition
original_list = [1, 2, 3]
repeated_list = original_list * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Repeating a list with a single element can quickly create lists of a specific length.
zeros = [0] * 5
print(zeros) # Output: [0, 0, 0, 0, 0]
You can use list repetition to make patterns, which can be useful in certain programming tasks or for creating test data.
pattern = ['A', 'B', 'C'] * 2
print(pattern) # Output: ['A', 'B', 'C', 'A', 'B', 'C']
List repetition does not modify the original list but instead creates a new list containing the repeated elements.
With lists that contain other lists (nested lists), repetition may produce unexpected behavior because of how Python handles list references. For example:
nested_list = [[1, 2]] * 3
nested_list[0][0] = 99
print(nested_list) # Output: [[99, 2], [99, 2], [99, 2]]
This happens because [[1, 2]] * 3
replicates references to the same inner list, not independent copies. You can avoid this by creating new inner lists explicitly using list comprehensions.
Repeating a list many times can result in a very large list, which could lead to memory issues if the repeated list becomes too large.
new_list = original_list * n