This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Sequences style guide

Style guide for sequences

face Josiah Wang

Here is a quick summary of what our favourite PEP 8 has to say about the coding conventions for lists, tuples, and for loops!

No spaces before the opening bracket

Like the parenthesis in functions, PEP 8 discourages adding a space before the opening bracket when indexing a list element.

# Recommended
numbers[2] = 5
print(numbers[2])
# No recommended!
numbers [2] = 5
print (numbers [2])

No spaces immediately inside the brackets

PEP 8 really does not like having whitespaces immediately inside brackets (and also parenthesis for functions). It just makes your code hard to read. See the following examples adapted from PEP 8.

# Good!
spam(ham[1])
# Not recommended!
spam( ham[ 1 ] )

Spaces in slicing operations

The slicing operator (:) should be treated as a binary operator with the lowest precedence. Remember that PEP 8 recommends grouping compound expressions by precedence for better readability, e.g. 1*2 + 3*4. When there are two colons (with the step parameter), both colons should have the same amount of spacing applied, unless when a parameter is omitted. Use your judgement - use spaces when it improves readability. Otherwise, avoid. The following are examples taken directly from PEP 8.

# Recommended
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
# Not recommended
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]