Short Ways to Manipulate Lists
List comprehensions provide a powerful, concise way to work with lists. Also, the map and filterfunctions can perform operations on lists using a different concise syntax.
Bad:
Good:
Bad:
Good:
Use enumerate to keep a count of your place in the list.
The enumerate function has better readability than handling a counter manually. Moreover, it is better optimized for iterators.
Read From a File
Use the with open syntax to read from files. This will automatically close files for you.
Bad:
Good:
The with statement is better because it will ensure you always close the file, even if an exception is raised.
Line Continuations
When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful sometimes but is preferably avoided, because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.
A preferred solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behavior holds for curly and square braces.
Bad:
Good:
However, more often than not having to split long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.