How to Standardize a List with Z-Score Normalization in Python
This code computes the z-score for each number in a list, standardizing the data to have zero mean and unit variance using the statistics module.
Python code
22 linesimport statistics
def z_score_normalize(values):
"""Standardize a list of numbers using z-score normalization."""
if not values or len(values) < 2:
raise ValueError("Need at least 2 values for meaningful z-score normalization")
mean = statistics.mean(values)
std_dev = statistics.stdev(values) # sample standard deviation
return [(x - mean) / std_dev for x in values]
if __name__ == "__main__":
data = [2, 4, 6, 8, 10]
normalized = z_score_normalize(data)
print(f"Original data: {data}")
print(f"Mean: {statistics.mean(data):.2f}")
print(f"Std dev: {statistics.stdev(data):.2f}")
print(f"Z-score normalized: {[f'{x:.2f}' for x in normalized]}")
print(f"Normalized mean: {statistics.mean(normalized):.2f}")
print(f"Normalized std dev: {statistics.stdev(normalized):.2f}")
Output
Original data: [2, 4, 6, 8, 10]
Mean: 6.00
Std dev: 3.16
Z-score normalized: ['-1.26', '-0.63', '0.00', '0.63', '1.26']
Normalized mean: 0.00
Normalized std dev: 1.00
How it works
The statistics.stdev function computes the sample standard deviation (using n-1 degrees of freedom), which is standard for normalizing a sample. The list comprehension [(x - mean) / std_dev for x in values] applies the z-score formula to each element, producing a new list where the mean becomes 0 and the standard deviation becomes 1. This transformation preserves the shape of the distribution while making it comparable across different datasets. The function raises a ValueError if the list has fewer than two elements, because sample standard deviation is undefined for a single value.
Common mistakes
- Using `statistics.pstdev` (population standard deviation) instead of `stdev` when the data is a sample, which gives slightly different normalization.
- Forgetting to handle empty or single-element lists, causing a `StatisticsError`.
- Dividing by zero if the standard deviation is 0 (e.g., all values identical).
- Modifying the original list in place instead of returning a new normalized list.
Variations
- Use `statistics.pstdev` if the list represents an entire population rather than a sample.
- Use a library like NumPy with `(data - np.mean(data)) / np.std(data)` for large datasets and faster computation.
Real-world use cases
- Preprocessing features for machine learning models to ensure each input feature has similar scale.
- Comparing test scores from different exam versions by converting raw scores to a common scale.
- Detecting outliers in sensor data by flagging readings with z-scores exceeding a threshold.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.