Python Line Continuation: Continue Code on the Next Line

Learn how Python line continuation works using parentheses, brackets, braces, and backslash, with examples for long expressions, strings, lists, function calls, and common errors.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python Line Continuation: Continue Code on the Next Line

Long expressions, argument lists, and literals are easier to read when you split them across several physical lines. Python does not let you break a line in the middle of arbitrary tokens, but it does support continuation: either implicit (inside matching (), [], or {}) or explicit (a backslash at the end of a line). This guide explains both styles, how they apply to strings and function calls, and mistakes that produce SyntaxError or surprising output.

For control flow in loops, see Python continue statement (different from line continuation). For catching runtime errors after code parses, see Python try except.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is line continuation in Python?

Line continuation means writing one logical Python statement or literal across more than one line in the source file. The lexer either treats newlines inside open (), [], or {} as insignificant until the closing delimiter (implicit continuation), or treats a backslash-newline pair as removing the line break (explicit continuation). Without one of those mechanisms, pressing Enter in the middle of a string or expression usually raises SyntaxError.

Here is one logical assignment split across two physical lines using parentheses—the newline after 40 does not end the statement:

python
answer = (
    40
    + 2
)
print(answer)
Output

That prints 42 as a single expression; the closing ) ends the statement.


Best way to continue code on the next line

The style recommended by PEP 8 is implicit continuation: wrap the expression in parentheses (or use a bracketed literal or call) and break after commas or operators. That avoids a fragile backslash at the edge of the editor and keeps diffs clean. Reserve the backslash for cases where adding parentheses would change semantics or look worse than a single continuation character.

For a long boolean condition, parentheses let each clause sit on its own line without backslashes:

python
files_ok = True
checksum_ok = True
expired = False
ready = (
    files_ok
    and checksum_ok
    and not expired
)
print(ready)
Output

That prints True; the whole assignment is still one statement.


Implicit line continuation with parentheses, brackets, and braces

Inside a pair of parentheses, square brackets, or curly braces, Python allows line breaks between tokens. The newline is treated as whitespace until the closing delimiter. This works for arithmetic in parentheses, list/tuple/set/dict literals, comprehensions, and function calls.

Continue long expressions with parentheses

You can split a long arithmetic or boolean expression across lines without a backslash:

python
total = (
    10
    + 2
    - 1
)
print(total)
Output

That prints 11; the parentheses only group for continuation and readability, not a separate tuple result.

Continue lists, tuples, sets, and dictionaries

Literals with [], (), {} naturally span lines—each element or entry can sit on its own row:

python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
]
config = {
    "host": "db.local",
    "port": 5432,
    "ssl": True,
}
print(len(matrix), config["port"])
Output

That prints 2 and 5432.

Continue function calls over multiple lines

Place the opening ( after the function name, then break before each argument:

python
def fetch(url, timeout, headers):
    return (url, timeout, headers)


result = fetch(
    "https://example.com/api",
    30,
    {"Accept": "application/json"},
)
print(result[0])
Output

The call is one statement; indentation under the opening ( is conventional for readability.


Explicit line continuation with backslash

A backslash (\) at the very end of a physical line escapes the newline so the next line is appended to the current logical line. You can use it for long expressions or continued string literals:

python
message = "Welcome to " + \
    "GoLinuxCloud " + \
    "tutorials"
print(message)

sum_vals = 2 + \
    3 + \
    4 + \
    6
print(sum_vals)
Output

The first print shows one concatenated string; the second prints 15.


Backslash vs parentheses: which should you use?

Use parentheses (implicit continuation) by default: it survives trailing spaces on the continued line edge more safely in teams, and nested calls already need parentheses. Use a backslash when wrapping in parentheses would be awkward (for example rare cases outside delimiters) or when continuing inside a string where implicit literal joining is not what you want. If either style works, prefer parentheses.

The same concatenated string can be written both ways; the parenthesized form has no continuation character at the end of each line:

python
with_parens = (
    "alpha "
    "beta "
    "gamma"
)
with_backslash = "alpha " + \
    "beta " + \
    "gamma"
print(with_parens == with_backslash)
print(with_parens)
Output

Both variables hold alpha beta gamma; the first line prints True.


Line continuation in Python strings

Strings need extra care because an open quote cannot span a raw newline unless you use triple quotes or explicit continuation.

Split a long string across multiple lines

Adjacent string literals inside parentheses are automatically concatenated at parse time, which gives you one logical string without embedded newline characters unless you include \n:

python
long_title = (
    "Python line continuation: "
    "parentheses, brackets, "
    "and strings"
)
print(long_title)
Output

That prints a single line of text with spaces as written.

Inside a double- or single-quoted string, a backslash at the end of the line continues the string on the next physical line without inserting a newline into the value:

python
s = "alpha beta gamma " + \
    "delta epsilon"
print(s)
Output

Triple-quoted strings vs line continuation

Triple-quoted strings (""" or ''') allow real newlines inside the literal—the newline characters become part of the string value. That is multiline data, not “continuation” that keeps one logical line of prose:

python
block = """Line one
Line two"""
print(repr(block))
Output

You will see \n in the representation between the two lines. For a single output line written across several source lines, use parenthesized literals or backslashes inside quotes instead of triple quotes unless you want those newlines stored.


Common errors in Python line continuation

SyntaxError from breaking a string incorrectly

If you open a string and press Enter before the closing quote, the lexer hits end-of-line while still inside the string:

python
mystring = "Welcome to
    GoLinuxCloud"
text
SyntaxError: unterminated string literal (detected at line ...)

Fix by closing each line’s fragment, using implicit concatenation in parentheses, using \ before the newline inside the string, or using triple quotes when embedded newlines are acceptable.

Backslash with trailing spaces

If a space (or tab) appears after \ but before the newline, the backslash no longer escapes the newline and you often get a syntax error or a stray backslash token. Treat “backslash is last on the line” as a hard rule; many editors can show trailing whitespace so you can strip it.

Comments after a backslash

Anything after \ on the same line—including # and a comment—means the backslash is not the final character, so continuation fails:

python
x = 1 + \  # meant to continue
    2
text
SyntaxError: unexpected character after line continuation character

Put the comment on its own line above the continued expression, or switch to parenthesized continuation.

Confusing line continuation with the continue statement

The keyword continue only applies inside for or while loops and jumps to the next iteration. It does not join lines in the source file. If you need loop control, read Python continue statement; for formatting long statements, use the continuation rules in this article.


Python line continuation quick reference table

Situation Preferred approach
Long arithmetic or conditions Wrap in () and break lines after operators
Long list / dict / set literals Use [] / {} and put elements on separate lines
Long function calls ( after name; one argument per line; trailing comma optional
Long string, single output line Parenthesized adjacent literals, or \ before newline inside quotes
Multiline string value (keep \n in data) Triple-quoted """..."""
Rare case without natural delimiters Trailing \ at true end of line

Summary

Python line continuation lets you format long code readably: implicit continuation inside (), [], or {} is the usual choice for expressions, literals, and calls; explicit backslash continuation works but is easy to break with trailing spaces or same-line comments. Strings require explicit techniques—parenthesized literal concatenation, backslash-newline inside the quotes, or triple quotes when newlines belong in the value—not a raw newline inside ordinary quotes. The continue statement is unrelated; it controls loops, not how the parser joins source lines.


References


Frequently Asked Questions

1. What is the best way to continue a long line in Python?

Prefer implicit continuation inside parentheses (), square brackets [], or curly braces {} so the parser joins physical lines into one logical line; use a trailing backslash only when those delimiters feel heavier than a single continuation character.

2. Can I break a string literal across two lines by pressing Enter inside the quotes?

Not in the middle of a quoted segment without closing the string first; that raises SyntaxError. Use parenthesized adjacent string literals, a backslash before the newline inside the string, or triple-quoted strings when you want real newline characters stored in the value.

3. Why does backslash line continuation fail even though I used a backslash?

The backslash must be the last character on the physical line; a trailing space after it, or any non-whitespace text after it on the same line (including a same-line comment), breaks continuation and typically produces a syntax error.

4. Is line continuation the same as the continue statement in a loop?

No. The continue statement skips to the next iteration of the innermost loop; line continuation only tells the parser how to join source lines before execution and does not affect control flow at runtime.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …