How to Normalize a List of Numbers in Python

This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 17 views 0 copies

Python code

31 lines
Python 3.9+
def normalize(data):
    """
    Normalize a list of numeric values to the range [0, 1].
    Returns a new list, leaving the original unchanged.
    """
    if not data:
        return []
    
    min_val = min(data)
    max_val = max(data)
    
    # Handle the edge case where all values are identical
    if min_val == max_val:
        return [0.0 for _ in data]
    
    normalized = []
    for value in data:
        scaled = (value - min_val) / (max_val - min_val)
        normalized.append(round(scaled, 4))
    return normalized


if __name__ == "__main__":
    # Example: normalize test scores
    scores = [45, 78, 92, 30, 67]
    result = normalize(scores)
    print("Original scores:", scores)
    print("Normalized scores:", result)
    
    # Show that original is unchanged
    print("Original still intact:", scores)

Output

stdout
Original scores: [45, 78, 92, 30, 67]
Normalized scores: [0.2419, 0.7742, 1.0, 0.0, 0.5968]
Original still intact: [45, 78, 92, 30, 67]

How it works

The function first checks for an empty list and returns an empty list to avoid errors. It then calculates the minimum and maximum values, which define the range for scaling. If all values are identical (min equals max), it returns a list of zeros to avoid division by zero. For each value, it applies the formula (value - min) / (max - min), which maps the minimum to 0 and the maximum to 1. The results are rounded to four decimal places for readability, and the original list remains unchanged because a new list is built.

Common mistakes

  • Forgetting to handle empty lists, causing ValueError when calling min() on an empty sequence.
  • Not handling the case where all values are equal, resulting in division by zero.
  • Using the built-in min and max functions on non-numeric data, causing TypeError.
  • Modifying the original list in place instead of returning a new list.

Variations

  1. Use a list comprehension: [round((x - min_val) / (max_val - min_val), 4) for x in data] for conciseness.
  2. Use the scikit-learn MinMaxScaler for more advanced scaling with feature_range control.

Real-world use cases

  • Preprocessing numerical features before training a machine learning model to ensure consistent scales.
  • Scaling sensor readings to a common 0–1 range for visualization on dashboards.
  • Normalizing user ratings from different systems to compare them on a uniform scale.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.