PythonPython StringsPython string joining

How do you join a list of strings?

Question 71 of 88 · Updated

On this page

Use separator.join(strings) to combine a list or other iterable of strings into one string. The separator is inserted between consecutive elements, without automatically adding a leading or trailing separator. Use an empty separator to combine fragments directly.

For example, ', '.join(['red', 'blue']) produces the string 'red, blue'.

The earlier concatenation lesson introduced join as an efficient alternative to repeatedly extending a growing string. This lesson focuses on its iterable contract, empty-field behavior, conversion policies, memory implications and practical text assembly.

1. Understand the separator and empty elements#

PYTHON
parts = ['A', '', 'B'] print('|'.join(parts)) print(repr('|'.join([])), repr('|'.join(['']))) print('|'.join(['', '']))

Output:

A||B
'' ''
|

The empty element between A and B is preserved. There are three input elements, so there are two separator occurrences. The method does not discard empty elements.

Input to joinResult with separator ''
[]''
['A']'A'
['A', 'B']'A\B'
['A', '', 'B']'A\\
['', '']'\'

For k input strings, the number of inserted separators is max(0, k - 1). If their total code-point length is S and the separator has length d, the result length is S + max(0, k - 1)*d.

Loading diagram…

The separator is the receiver of the method, not an argument to a list method. The result is a str, and joining an existing list does not mutate that list.

2. Joining is not limited to lists#

PYTHON
data = {'red': 2, 'blue': 1} print(','.join(data)) print(','.join(sorted({'blue', 'red'}))) print('-'.join('abc'))

Output:

red,blue
blue,red
a-b-c

Join accepts an iterable whose elements are strings. A tuple, list, generator or custom iterable can be used.

The result follows the order in which elements are yielded. Iterating a dictionary yields keys in insertion order, not values or key-value pairs. Iterating a set does not provide an application-defined ordering; sort the values first when a deterministic sorted result is required.

A string is itself iterable, yielding one-code-point strings. Thus joining a string directly can insert a separator between its code points, rather than treating it as a single fragment.

Do not accidentally pass a single filename or message when the function expects a collection of complete strings. If a single string is intended as one element, place it in a one-element list or tuple.

3. Generators are consumed, not joined lazily#

PYTHON
parts = (str(n) for n in range(3)) print(','.join(parts)) print(repr(','.join(parts)))

Output:

0,1,2
''

A generator yields its elements once. Joining it consumes those elements, so the second call sees an exhausted generator and returns an empty string.

Using a generator expression can avoid writing an explicit list comprehension, but join still needs to produce a complete string. In CPython, joining a general iterator can involve collecting its items into an intermediate sequence before constructing the final result. It is not a constant-memory streaming operation.

Loading diagram…

This diagram summarizes a typical CPython assembly path. The language does not prescribe allocation order or the exact point at which an invalid iterator element is detected. An iterator can raise its own exceptions during consumption; it may already have performed observable work before join fails.

Never pass an infinite iterable to join expecting a lazily generated string. Bound the input or write incremental output to an appropriate stream.

4. Joining numbers and handling missing values#

Join does not automatically convert non-string elements. For numeric values, explicitly convert them using str or a formatting expression when that representation is appropriate.

Missing values require a separate decision. Consider a simple display record where None represents an empty field but zero and False must remain visible.

PYTHON
def render_row(values): return '|'.join('' if v is None else str(v) for v in values) print(render_row(['A', None, 0, False]))

Output:

A||0|False

This preserves the field count and distinguishes missing values from legitimate falsey values. A filter based on truthiness would also discard 0, False and empty strings, which may change the meaning of the record.

For a stricter interface, reject any unexpected non-string element instead of automatically converting it. For human-readable output, a type-specific formatter can control numerical precision, dates or other representations.

The function above implements a deliberately simple display convention, not an escaping mechanism or a reversible serialization format. If values may contain the delimiter, a reader cannot necessarily reconstruct the original fields.

5. Joining lines and controlling the final newline#

PYTHON
parts = ['a', 'b'] text = '\n'.join(parts) print(repr(text)) print(repr(text + '\n')) print(parts)

Output:

'a\nb'
'a\nb\n'
['a', 'b']

The newline separator appears between lines. The first result has no automatically appended final newline; the second explicitly adds one. The original list remains unchanged.

For a file format requiring a terminator after every record, define how empty input is handled before appending a final terminator. For example, an empty file and a file containing one empty line are not necessarily interchangeable.

When generating a large document, consider writing each formatted line directly to a file or text stream rather than joining all lines into a single string. Choose the encoding, newline policy and error handling appropriate to the destination.

6. Joining is not CSV serialization#

PYTHON
import csv from io import StringIO out = StringIO(newline='') csv.writer(out, lineterminator='\n').writerow(['Ada', 'New Delhi, India']) print(repr(out.getvalue()))

Output:

'Ada,"New Delhi, India"\n'

A plain comma join of these fields would produce ambiguous comma-delimited text. The CSV writer inserts the required quoting and record terminator according to its dialect.

Similarly, joining text with slashes is not a substitute for a filesystem path API, and joining values with ampersands is not a substitute for URL query encoding. Use json.dumps for JSON, csv.writer for CSV, pathlib for filesystem paths and appropriate parameter interfaces for database commands.

Join merely combines strings. It does not escape separators, validate destinations or protect against injection.

7. Joining text and binary data#

PYTHON
parts = ['é', '🙂'] print('|'.join(parts)) print(b'|'.join(p.encode('utf-8') for p in parts).hex())

Output:

é|🙂
c3a97cf09f9982

The str separator joins Unicode text. A bytes separator joins bytes-like elements according to the binary operation's contract. Mixing bytes and str directly raises TypeError in ordinary str.join.

The second expression encodes each input fragment as UTF-8 and joins the resulting byte strings with the ASCII pipe byte. The hexadecimal display shows the actual byte representation.

For encodings or protocols with state, byte-order markers or framing requirements, encoding each fragment separately may differ from encoding the complete joined text. Choose an explicit encoding boundary based on the format's requirements.

8. Error handling#

OperationExpected exception
','.join([1,2])TypeError
','.join(['a',None])TypeError
','.join([b'a'])TypeError
','.join(12)TypeError

The first three inputs contain invalid element types; the fourth is not iterable. These four cases were executed independently and confirmed.

Do not catch TypeError broadly and discard invalid elements without an explicit policy. This can conceal corrupted data and change the number or order of fields. Validate at the appropriate input boundary and provide meaningful errors when a contract is violated.

For custom iterables, exceptions raised during iteration can propagate independently of join's element validation.

9. Time and space complexity#

Let k be the number of strings, S the sum of their lengths, and d the length of the separator. The resulting length is L = S + max(0, k - 1)*d.

For already available ordinary strings, a typical CPython join requires O(k + L) time. The k term accounts for examining elements even if they are empty. The L term accounts for constructing the output. The actual cost of producing an iterable's elements or converting them into strings must be added separately.

When a nontrivial string is materialized, result storage is generally O(L) under a bounded-width code-point model. A general iterator may also require O(k) temporary references and retain the generated fragments until assembly completes. Exact allocation behavior and special-case object reuse are implementation details.

The earlier concatenation lesson explains the possible quadratic repeated-copy pattern of growing a string through repeated addition. Join avoids that pattern for a collection of fragments, but it is not automatically the fastest approach for every workload. Measure representative workloads if performance is important.

Enforce sensible limits on both field count and output length when input comes from untrusted or potentially enormous collections. A generator alone does not prevent large allocations.

10. Choose the correct assembly method#

RequirementSuitable interface
Join known string fragments without separators''.join(parts)
Insert a separator between fieldssep.join(parts)
Convert numeric values using an explicit representationJoin formatted strings
Retain empty fieldsJoin without truthiness filtering
Generate quoted CSV recordscsv.writer
Produce output larger than available memoryIncremental writing with bounded input
Combine a small number of known stringsConcatenation or f-string

The key distinction from split is the direction of the operation: split produces fields from text, while join builds text from fields. As explained in the splitting lesson, unlimited splitting on a nonempty literal separator followed by joining with that same separator reconstructs the original string. The inverse does not necessarily reconstruct arbitrary original fields if the fields themselves contain the separator.

Interview-ready answer#

Use separator.join(iterable) to combine an iterable of strings. The separator appears only between consecutive elements, and empty elements are preserved. Join accepts lists, tuples, generators and other iterables, but each yielded element must be a string. Non-string values need explicit conversion or validation. A generator is consumed, and the result is a complete string rather than a lazy stream. Under the usual CPython cost model, joining k existing strings into L output code points takes O(k + L) time. Use a dedicated serializer when delimiters, quoting or structured-data semantics matter.

Official references#

Verification note: Seven runnable Python example groups matched their expected outputs in independent namespaces on CPython 3.13.5. Four expected TypeError tests passed. Across 500 seeded randomized lists and separators, 1,000 assertions checked the output against independent separator insertion and verified the output-length formula. Two fenced Mermaid diagrams were manually reviewed; no local Mermaid parser or CLI was available, and public rendering was not verified. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design