To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries. As an alternative, you can also use the backslash
\ just in front of the line break to escape the newline character.
After publishing an article on how to condense multiple lines into a single line of Python code, many Finxters asked: How to break a long line to multiple lines in Python? This article shows you the best way of breaking a long-winded one-liner into multiple lines to improve readability and unclutter your code.
Problem: Given a long line of Python code. How to break it into multiple lines?
There are multiple ways of breaking this into multiple lines. Let’s get an overview first:
Exercise: Run the code. What’s the output? Modify Method 3 and write it as a one-liner again!
We now dive into each of those methods.
Method 1: Implicit Line Continuation — Use Parentheses to Avoid Line Break Backslashes
The PEP 8 – Style Guide argues that the best way to break long lines into multiple lines of code is to use implicit line continuation by using parentheses. An opening parenthesis signals to Python that the expression has not finished, yet. So, the Python interpreter keeps looking in the following line to close the currently open expression. This way, you can rewrite any Python one-liner to a multi-liner just by using one or more pairs of parentheses.
Here’s the original statement from the PEP 8 style guide (emphasis by me):
The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.
Do you need an example for implicit line continuation? Here it is:
# Long Line a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) # Implicit Line Continuation b = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) print(a) # [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)] print(b) # [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]
The long line
a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) zips together two lists to obtain the result
[('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]. You can rewrite this into multiple lines by using the existing parentheses. Note that it is good style to hierarchically align the lines in Python. In our example, the two lists are aligned when creating the multi-line statement to assign the variable
Remember: you can always break lines if an opened bracket, parenthesis, or bracelet has not been closed!
Method 2: Explicit Line Continuation — Use the Line Break Backslash \
However, what if you don’t want to introduce new parentheses into your expression? Can you still break up a one-liner into multiple lines?
The answer is: yes! Just use the line break backslash
\ which you may call explicit line continuation. With the backslash, you can break at any position in your expression. Technically, the backslash character “escapes” the newline character that follows immediately afterwards. By escaping the newline character, it loses its meaning and Python simply ignores it. This way, you don’t have to introduce any new parentheses.
Here’s a minimal example that shows the flexibility with which you can break new lines this way:
a = 1 + 2 + 3 + 4 - 5 * 2 b = 1 \ + 2 + \ 3 + 4\ - 5 *\ 2 print(a) # 0 print(b) # 0
Seeing the messy code in the previous example may cause you to ask:
I’ll give the following answer based on the PEP 8 Style Guide (highlights by me):
For decades the recommended style was to break after binary operators. But this can hurt readability in two ways:
- the operators tend to get scattered across different columns on the screen, and
- each operator is moved away from its operand and onto the previous line.
Here, the eye has to do extra work to tell which items are added and which are subtracted:
# Wrong: results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)
To solve this readability problem, mathematicians and their publishers follow the opposite convention.
Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” .
Thus, the following code is proposed:
# Correct: results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)
You can do both in Python but you should prefer the latter to improve readability of your code!
Method 3: Break a String by Using a Multi-Line String with Triple Quotes
Example: Say, you have the following long string from Romeo and Juliet:
s = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant'
Note the newline character in the string: it’s really a multip-line string! Can you rewrite this into multiple lines to improve readability?
You can restructure strings by using the triple quotes that allows you to define a multi-line string without the newline character
'\n' in the string. This significantly improves readability of multi-line strings! Here’s an example:
s1 = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant' # MULTI-LINE s2 = '''Mistress! what, mistress! Juliet! fast, I warrant her, she: Why, lamb! why, lady! fie, you slug-a-bed! Why, love, I say! madam! sweet-heart! why, bride! What, not a word? you take your pennyworths now; Sleep for a week; for the next night, I warrant''' print(s1 == s2) # True
These are two ways of defining the same string. If you compare them, the result is
True. However, the second way is far more readable and should be preferred!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.