PythonArraysBeginner

List concatenation (+) and repeat (*)

Creates new lists by concatenating or repeating elements.

Review the syntaxStudy the examplesOpen the coding app
combined = a + b
repeated = a * n

This 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

1

Basic Sequence Concatenation

list_one = [10, 20]
list_two = [30, 40]
result = list_one + list_two
Output:
[10, 20, 30, 40]

The + operator merges two lists into a third new list instance, leaving the original lists unchanged.

2

String Element Repetition

status = ['pending']
queue = status * 3
Output:
['pending', 'pending', 'pending']

Repeats the references to the string 'pending' three times in a new list. Since strings are immutable, this is safe.

3

Deep Reference Limitation

nested = [[0]] * 3
nested[0][0] = 99
print(nested)
Output:
[[99], [99], [99]]

Updating one inner list updates all because they are references to the same object in memory.

Debug faster

Common Errors

1

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] + 3
2

LogicError

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

Python 3.8+

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.