How to Break Long Lines in Python

How to break lines in Python

Python supports implicit line continuation. This means you can break long lines of code.

For example, instead of this:

math_students = ["Alice", "Bob", "Charlie", "David", "Emmanuel"]

You can write it like this:

math_students = [
    "Alice",
    "Bob",
    "Charlie",
    "David",
    "Emmanuel"
]

As a matter of fact, you should limit all lines of code to the maximum of 79 characters.

Today, you are going to learn when and how to break long lines in Python.

Breaking Long Lines of Code in Python

Breaking lines increases the total number of lines of code. But at the same, it can drastically improve the readability of your code.

It is recommended not to have lines of code longer than 79 characters.

Python supports implicit line continuation. This means any expression inside the parenthesis, square brackets, or curly braces can be broken to multiple lines.

For example, here is a long print statement is broken into multiple lines in a couple of ways:

print("Alice", "Bob", "Charlie", "David", "Emmanuel",
      "Farao", "Gabriel", "Hilbert", "Isaac")

print(
    "Alice", "Bob", "Charlie",
    "David", "Emmanuel", "Farao",
    "Gabriel", "Hilbert", "Isaac"
)

print(
    "Alice",
    "Bob",
    "Charlie",
    "David",
    "Emmanuel",
    "Farao",
    "Gabriel",
    "Hilbert",
    "Isaac"
)

There are many ways you can break long lines in Python. You may want to check the official style guide that explains best practices more thoroughly.

Before jumping into examples, notice that there is a way to automatize the line-breaking process.

How to Auto-Break Long Lines of Code in Python

Popular code editors allow you install plugins that enforce code style guidelines.

A cool feature of these plugins is you can usually auto-format code. In other words, the plugin automatically takes care no line exceeds the 79 character “limit”.

For example, in VSCode it is possible to automatically format code on save.

Next up, let’s see some examples when you may want to split expressions into multiple lines.

How to Break a String into Multiple Lines

To break a string to multiple lines, wrap each string in the new line inbetween a pair of double quotation marks.

For instance, you can do this:

print(
    "This happens to be"
    " so long string that"
    " it may be a better idea"
    " to break the line not to"
    " extend it further to the right"
)

But you cannot do this:

print(
    "This happens to be
    so long string that
    it may be a better idea
    to break the line not to
    extend it further to the right"
)

Break a Function Arguments into Multiple Lines

If your function takes a number of arguments that extends line of code far to the right, feel free to break the expression into multiple lines.

For example, instead of doing this:

def example_function(first_number, second_number, third_number, fourth_number, fifth_number):
    pass

You can do this:

def example_function(
    first_number,
    second_number,
    third_number,
    fourth_number,
    fifth_number
):
    pass

Break a List into Multiple Lines

For example, let’s create a 3×3 matrix using a list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

This is fine, but as you may know, a matrix is written in a table format. This makes it look more like a table of values.

To follow this convention in Python, you can split the matrix (the list of lists) into multiple lines:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Break a Dictionary into Multiple Lines

Just like breaking a list declaration into multiple lines, you can do it with a dictionary.

For instance, instead of a long expression like this:

student = {"name": "Alice", "graduated": False, "married": False, "age": 23, "hobbies": ["Jogging", "Gym", "Boxing"]}

Let’s split the dictionary into a bunch of lines to make it more understandable:

student = {
    "name": "Alice",
    "graduated": False,
    "married": False,
    "age": 23,
    "hobbies": ["Jogging", "Gym", "Boxing"]
}

Break Mathematical Operations into Multiple Lines

To split a chain of binary operations, break the line before the operator. This makes the code more readable as the binary operators are not all over the place.

For example, instead of doing this:

income = gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest

You can do this:

income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

This example is directly from the PEP-0008 style guide.

Break Comparisons into Multiple Lines

Like any other expression, comparisons can also take some space. To avoid too long chains of comparisons, you can break the line.

For instance:

if (is_rainy == True and
    is_hot == True and
    is_sunny == True and
    is_night == True):
    print("How is that possible...?")

Conclusion

Python’s implicit continuation makes it possible to break long expressions into multi-line expressions. This is useful for code readability.

To break an expression into multiple lines, wrap the expression around a set of parenthesis and break it down as you want.

If the expression is already in a set of parenthesis, square brackets, or curly braces, you can split it to multiple lines. This is true for example for lists, tuples, and dictionaries.

Thanks for reading. I hope you like it.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.