Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

Concatenation in Python is the operation of joining two or more sequence data types (such as strings, lists, or tuples) end-to-end to form a single, new sequence. While the standard addition operator (+) strictly requires operands to be of the exact same type due to Python’s strong typing, other concatenation mechanisms, such as in-place augmented assignment (+=) on mutable sequences or iterable unpacking, can accept arbitrary iterables.

String Concatenation

Strings in Python are immutable. Therefore, concatenation operations always allocate a new string object in memory representing the combined sequence. The + and += Operators The standard addition operator is overloaded to handle sequence concatenation via the __add__ dunder method. The augmented assignment operator (+=) rebinds the variable to the newly created string.
str1 = "foo"
str2 = "bar"
result = str1 + str2  # "foobar"

str1 += "baz"         # Rebinds str1 to "foobaz"
Formatted String Literals (f-strings) Introduced in Python 3.6, f-strings evaluate expressions at runtime and format them directly into a single string. This is the modern, idiomatic standard for combining string variables and literals.
str1 = "foo"
str2 = "bar"
result = f"{str1}{str2}"  # "foobar"
The str.join() Method For concatenating an iterable of strings, str.join() is the computationally optimal approach. It calculates the total required memory once before allocating the new string, avoiding the quadratic time complexity associated with chained + operations.
iterable = ["foo", "bar", "baz"]
separator = "-"
result = separator.join(iterable)  # "foo-bar-baz"
Implicit Literal Concatenation Adjacent string literals separated only by whitespace are evaluated and concatenated at compile-time by the Python parser. This is a syntax feature and does not work with variables or expressions.
result = "foo" "bar"  # "foobar"

List and Tuple Concatenation

Lists (mutable) and tuples (immutable) utilize similar operators but exhibit fundamentally different memory behaviors and type constraints during concatenation. The + Operator Creates a completely new list or tuple containing shallow copies of the elements from the operands. Both operands must be of the exact same type.
list_result = [1, 2] + [3, 4]      # [1, 2, 3, 4]
tuple_result = (1, 2) + (3, 4)     # (1, 2, 3, 4)
Iterable Unpacking Introduced in Python 3.5 (PEP 448), the unpacking operator (*) extracts elements from iterables directly into a new sequence literal. This is a highly idiomatic method for concatenating multiple sequences, allowing you to seamlessly combine different iterable types.
list1 = [1, 2]
tuple1 = (3, 4)


# Unpacking into a new list
combined_list = [*list1, *tuple1]    # [1, 2, 3, 4]


# Unpacking into a new tuple
combined_tuple = (*list1, *tuple1)   # (1, 2, 3, 4)
In-Place Concatenation (+= and extend()) For mutable sequences like lists, += invokes the __iadd__ magic method, which modifies the object in place. Because __iadd__ acts identically to list.extend(), it accepts any iterable, not just lists. For immutable sequences like tuples, += falls back to __add__, which strictly requires the same type and rebinds the variable to a newly allocated object.

# List (Mutable: In-place modification accepts ANY iterable)
l1 = [1, 2]
l1 += (3, 4)          # Tuple iterable: l1 is mutated to [1, 2, 3, 4]
l1 += "ab"            # String iterable: l1 is mutated to [1, 2, 3, 4, 'a', 'b']
l1.extend({5, 6})     # Set iterable: l1 is mutated to [1, 2, 3, 4, 'a', 'b', 5, 6]


# Tuple (Immutable: Rebinding requires matching types)
t1 = (1, 2)
t1 += (3, 4)          # t1 is rebound to a new tuple (1, 2, 3, 4)

Sequence Repetition (Multiplicative Concatenation)

The * operator is overloaded for sequences to perform repetition, which is effectively concatenating a sequence to itself a specified integer number of times via the __mul__ method.
str_rep = "a" * 3       # "aaa"
list_rep = [0] * 4      # [0, 0, 0, 0]
Note: When repeating lists containing mutable objects, the new list contains references to the original objects, not deep copies.

Lazy Concatenation via itertools.chain

For memory-efficient concatenation of large, infinite, or mixed-type iterables, itertools.chain() yields elements from the first iterable until exhausted, then proceeds to the next. It performs lazy evaluation without allocating a new combined sequence in memory.
import itertools

iter1 = [1, 2, 3]
iter2 = (4, 5, 6)
chained = itertools.chain(iter1, iter2)


# Evaluates lazily, yielding one item at a time
result = list(chained)  # [1, 2, 3, 4, 5, 6]
Master Python with Deep Grasping Methodology!Learn More