Syntactic Sugar
Augmented assignment operators are concise and clear.
x += 1 # Equivalent to `x = x + 1`
x *= 2 # Equivalent to `x = 2 * x`
Tuples can be unpacked with assignment.
tup = (1, 2)
a, b = tup # Equivalent to `a = tup[0]; b = tup[1]`
Functions can return multiple values as a tuple without parentheses.
def min_max(items):
return min(items), max(items)
minimum, maximum = min_max([1, 2, 3, 4, 5])
The statement pass maintains grammar for empty bodies.
# Wrong: Indentation Error
def incomplete_function():
# Correct
def incomplete_function():
pass
# Correct
for i in range(10):
pass
Comprehension concisely makes lists, sets and dictionaries.
even_squares = [x**2 for x in range(10) if x % 2 == 0]
Use with-statements when there is a natural setup and exit. For example, the following two code snippets are equivalent.
f = open("example.txt", "r")
try:
contents = f.read()
finally:
f.close()
with open("example.txt", "r") as f:
contents = f.read()