stdev() method in Python statistics module (original) (raw)

Last Updated : 11 Jul, 2025

The stdev() function in Python's statistics module is used to calculate the standard deviation of a dataset. It helps to measure the spread or variation of values in a sample. **Standard deviation (SD) measures the spread of data points around the mean. A low SD indicates data points are close to the mean, while a high SD shows they are spread out. Unlike variance, SD is in the same units as the data, making it easier to interpret.

formula

Standard deviation formula

**Where:

**Example:

Python `

import statistics

a = [1, 2, 3, 4, 5] print(statistics.stdev(a))

`

Syntax of stdev() method

statistics.stdev(data, xbar=None)

**Parameters:

**Returns: The standard deviation of the values in the dataset.

Examples of stdev() method

**Example 1: In this example, we calculate the standard deviation for four datasets to measure the spread, including integers, floating-point numbers and negative values.

Python `

from statistics import stdev

different datasets

a = (1, 2, 5, 4, 8, 9, 12) b = (-2, -4, -3, -1, -5, -6) c = (-9, -1, 0, 2, 1, 3, 4, 19) d = (1.23, 1.45, 2.1, 2.2, 1.9)

print(stdev(a)) print(stdev(b)) print(stdev(c)) print(stdev(d))

`

Output

3.9761191895520196 1.8708286933869707 7.8182478855559445 0.41967844833872525

**Example 2: In this example, we calculate the standard deviation and variance for a dataset to measure the spread of values.

Python `

import statistics a = [1, 2, 3, 4, 5]

print(statistics.stdev(a)) print(statistics.variance(a))

`

Output

1.5811388300841898 2.5

**Example 3: In this example, we calculate the standard deviation by providing a precomputed mean using the xbar parameter in the stdev() function to avoid recalculating the mean.

Python `

import statistics a = (1, 1.3, 1.2, 1.9, 2.5, 2.2)

Precomputed mean

mean_val = statistics.mean(a) print(statistics.stdev(a, xbar=mean_val))

`

**Example 4: In this example, we attempt to calculate the standard deviation of a dataset with a single data point. Since stdev() requires at least two points, it raises a StatisticsError, which is handled using a try-except block.

Python `

import statistics

single data point

a = [1]

try: print(statistics.stdev(a)) except statistics.StatisticsError as e: print("Error:", e)

`

**Output

Error: stdev requires at least two data points