List concatenation (+) and repeat (*)
Creates new lists by concatenating or repeating elements.
combined = a + b
repeated = a * nThis static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Creates new lists by concatenating or repeating elements.
In Python, list concatenation using the '+' operator creates a completely new list object by performing a shallow copy of all element references from the source lists into the target. This operation has a time complexity of O(n + m), where n and m are the lengths of the input lists. The repetition operator '*' implements list multiplication, producing a new list that repeats the references from the original list 'n' times. A critical technical edge case involves mutable objects: if a list contains a mutable item (like a nested list or dictionary), the '*' operator copies the reference to that specific object multiple times. Consequently, modifying a nested object at one index will reflect across all indices because they all point to the same memory address. For generating independent nested structures, developers should use list comprehensions instead of the repetition operator.
Quick reference
Syntax
combined = a + b
repeated = a * n
See it in practice
Examples
Basic Sequence Concatenation
list_one = [10, 20]
list_two = [30, 40]
result = list_one + list_two[10, 20, 30, 40]
The + operator merges two lists into a third new list instance, leaving the original lists unchanged.
String Element Repetition
status = ['pending']
queue = status * 3['pending', 'pending', 'pending']
Repeats the references to the string 'pending' three times in a new list. Since strings are immutable, this is safe.
Deep Reference Limitation
nested = [[0]] * 3
nested[0][0] = 99
print(nested)[[99], [99], [99]]
Updating one inner list updates all because they are references to the same object in memory.
Debug faster
Common Errors
TypeError
Cause: Attempting to concatenate a list with a non-list type (like an integer or string) using the + operator.
Fix: Ensure the second operand is also a list by wrapping it in square brackets.
bad_concat = [1, 2] + 3LogicError
Cause: Using list repetition for initializing a matrix or grid of lists, causing shared state between rows.
Fix: Use a list comprehension to ensure each inner list is a unique object.
matrix = [[0] * 3 for _ in range(3)]Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Creates new lists by concatenating or repeating elements.
TypeError: Ensure the second operand is also a list by wrapping it in square brackets. LogicError: Use a list comprehension to ensure each inner list is a unique object.