How to Normalize a List of Numbers to the 0-1 Range in Python
Scale a list of numbers so the minimum becomes 0 and the maximum becomes 1 using min-max normalization.
Python code
15 linesdef min_max_normalize(values):
"""Normalize a list of numbers to the [0, 1] range."""
if not values:
return []
min_val = min(values)
max_val = max(values)
if min_val == max_val:
return [0.0] * len(values)
return [(x - min_val) / (max_val - min_val) for x in values]
if __name__ == "__main__":
data = [10, 20, 30, 40, 50]
normalized = min_max_normalize(data)
print(normalized)
Output
[0.0, 0.25, 0.5, 0.75, 1.0]
How it works
Min-max normalization rescales data linearly so the smallest value maps to 0.0 and the largest to 1.0. The function first checks for an empty list to avoid errors, then computes the minimum and maximum. If all values are equal, it returns a list of zeros to prevent division by zero. Each value is transformed using the formula (x - min) / (max - min), which preserves relative spacing between numbers.
Common mistakes
- Forgetting to handle empty lists, causing min() to raise a ValueError
- Not handling the case where all values are identical, leading to division by zero
- Using integer division in Python 2, but this is fine in Python 3 where / always returns a float
Variations
- Use a list comprehension with a generator to avoid storing intermediate values
- Implement with NumPy for large arrays: (values - min) / (max - min)
Real-world use cases
- Preprocessing features for machine learning models so they use a common scale before training.
- Scaling sensor readings from different ranges to make them comparable in dashboards or alerts.
- Normalizing pixel intensity values in image processing before feeding them into a neural network.
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.