Integer Division: float vs int
-
In Python 2, dividing two integers with
/performs integer division:1 / 2 # Output: 1 -
In Python 3,
/always performs floating-point division:1 / 2 # Output: 0.5 -
Use
//for integer (floor) division in both Python 2 and 3:1 // 2 # Output: 0
Mutable Default Arguments
def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list
print(append_to_list(1)) # [1]
print(append_to_list(2)) # [1, 2] # Not [2]!
Pitfall: Default mutable arguments are shared across function calls.
Solution: Use None as the default and create a new list inside the function.
def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list
Variable Binding in Loops (Late Binding)
funcs = [lambda: x for x in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
Pitfall: All lambdas capture the same variable, which ends up as the last value.
Solution: Use default arguments to capture the current value.
funcs = [lambda x=x: x for x in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
Chained Comparisons
x = 5
print(1 < x < 10) # True
print((1 < x) < 10) # True, but not the same!
Note: Python supports chained comparisons, but be careful with parentheses.
List Multiplication for Nested Lists
matrix = [[0] * 3] * 3
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Pitfall: All rows reference the same list.
Solution: Use a list comprehension:
matrix = [[0] * 3 for _ in range(3)]
Floating Point Precision
print(0.1 + 0.2 == 0.3) # False
Reason: Floating point arithmetic is not always exact.
Solution: Use math.isclose() for comparisons.
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
References
๐ข In-Article Ad (Development Mode)
Comments