
Image by Author | Canva
Introduction
Probability distributions are at the heart of statistics and data science. They describe how values are spread out, whether that’s the roll of a die, the time between emails, or the outcome of an experiment.
In this article, we’ll explore ten Python one-liners that demonstrate different distributions and core statistical ideas.
Note that while these are a collection of 10 short snippets, the bulk of the work in each case is being performed by a single line of Python. Each snippet is short, clear, and focused on building intuition. They’re not meant for production systems but as a way to learn quickly and visualize how probability works.
1. Uniform Distribution
The uniform distribution is the simplest way to model randomness. Every value in the specified range has an equal chance of being chosen.
import random # Generate 10 random numbers between 0 and 1 from a uniform distribution data = [random.uniform(0, 1) for _ in range(10)] print(data)
This one-liner uses random.uniform(0, 1) to generate numbers where every value between 0 and 1 is equally likely. The list comprehension repeats this process ten times.
Uniform distributions are often used when you want unbiased random sampling within a range. For example, simulating dice rolls, shuffling cards, or testing algorithms that require randomness all rely on the idea of uniform probability.
2. Normal (Gaussian) Distribution
The normal distribution is the most widely used in statistics. It’s the classic “bell curve” where most values cluster around the mean, and probabilities fall symmetrically as you move further away from the center.
import numpy as np # Generate 10 random numbers from a normal distribution with mean=0 and std=1 data = np.random.normal(0, 1, 10) print(data)
In the code sample, numpy.random.normal(0, 1, 10) generates ten numbers drawn from a normal distribution with a mean of 0 and a standard deviation of 1. Most values will fall close to zero, while fewer values will be far out in the tails.
The normal distribution underpins much of statistics, from hypothesis testing to regression modeling. Thanks to the Central Limit Theorem, many real-world processes end up approximately normal, even when the underlying data is more complex.
3. Binomial Distribution
The binomial distribution models repeated experiments with two possible outcomes, such as heads or tails in coin flips.
import numpy as np # Simulate 10 experiments of flipping a fair coin 5 times data = np.random.binomial(n=5, p=0.5, size=10) print(data)
In the code above, each experiment simulates flipping a coin 5 times (n=5). With p=0.5, each flip has an equal probability of landing heads or tails. The result tells you how many heads appeared in each experiment, repeated 10 times.
The binomial distribution is useful when dealing with discrete probability. It’s used to estimate probabilities of success or failure across trials, such as quality checks in manufacturing, click-through rates in online ads, or genetic trait inheritance in biology.
4. Poisson Distribution
The Poisson distribution models the number of times an event occurs within a fixed interval of time or space. This is useful when events happen independently and at a constant average rate, such as the number of emails you receive in an hour.
import numpy as np # Simulate the number of events occurring in 10 one-hour intervals, with an average of 3 per hour data = np.random.poisson(lam=3, size=10) print(data)
In the code above, lam=3 sets the average rate of events to 3 per hour, and size=10 generates values for 10 intervals. Each number represents the number of events that occurred in one simulated interval.
The Poisson distribution is central to queueing theory, telecommunications, and reliability engineering. For example, it can be used to model call arrivals at a call center or the number of server requests per second.
5. Quick Visualization with Matplotlib
Visualizing data is essential for building intuition about distributions. Python’s Matplotlib library makes this easy with just one line of code.
import matplotlib.pyplot as plt import numpy as np # Generate 1000 samples from a normal distribution data = np.random.normal(0, 1, 1000) # Plot a histogram of the data plt.hist(data, bins=30) plt.show()

Image by Author
The call to plt.hist(data, bins=30) creates a histogram with 30 bins, showing how the data is distributed. In this case, the values form the familiar bell-shaped curve of the normal distribution.
Histograms are one of the most powerful ways to quickly see the shape, spread, and skewness of data. Even advanced visualizations like kernel density estimates often start from the same foundation.
6. Sampling without Replacement
In statistics, sampling without replacement means that once an element is chosen, it cannot be picked again. This method is common in surveys and experiments where duplication is not allowed.
import random # Select 5 unique numbers from 1 to 20 data = random.sample(range(1, 21), 5) print(data)
Here, random.sample(range(1, 21), 5) picks five distinct integers between 1 and 20. The key feature is uniqueness; each number appears only once.
This concept is critical in fields like survey sampling and machine learning cross-validation, where ensuring a fair and non-repetitive draw is important.
7. Calculating a Sample Mean
The mean is the simplest statistical summary, showing the central tendency of a dataset. In practice, it tells you the average outcome of a sample.
import numpy as np # Generate 10 random numbers from a uniform distribution data = np.random.uniform(0, 10, 10) # Calculate the mean in one line mean_value = np.mean(data) print(mean_value)
In the code sample, np.mean(data) computes the arithmetic average of the generated sample. If you prefer pure Python, you can also use sum(data)/len(data).
The mean is often the first number reported in data analysis. While easy to compute, it is also sensitive to outliers and should be used with an awareness of the data’s distribution. You can learn more from the NumPy mean documentation.
8. Cumulative Distribution Function (CDF)
The cumulative distribution function (CDF) describes the probability that a random variable takes on a value less than or equal to a given threshold. It’s a way of showing how probabilities accumulate.
import numpy as np from scipy import stats # Generate 10 random samples from a normal distribution data = np.random.normal(0, 1, 10) # Compute CDF values for each data point cdf_values = stats.norm.cdf(data, loc=0, scale=1) print(cdf_values)
In this code example, stats.norm.cdf calculates the cumulative probability for each value in data. If a value is near zero (the mean), the CDF will be around 0.5, meaning half of the distribution lies below it.
CDFs are widely used in statistical inference, reliability analysis, and model evaluation. You can check the SciPy stats CDF reference for more details.
9. Hypothesis Testing with p-values
Hypothesis testing allows us to check whether a sample provides enough evidence to reject a claim about the population. The p-value tells us how likely the observed data would be to occur if the claim (null hypothesis) were true.
import numpy as np
from scipy import stats
# Generate a sample of 20 values from a normal distribution with mean=0
data = np.random.normal(0, 1, 20)
# Perform a one-sample t-test against the hypothesized mean = 0
t_stat, p_value = stats.ttest_1samp(data, 0)
print("t-statistic:", t_stat, "p-value:", p_value)
In the code above, stats.ttest_1samp checks if the mean of the sample differs significantly from zero. The output gives the test statistic and the corresponding p-value. A small p-value (commonly < 0.05) suggests the sample mean is unlikely under the null hypothesis.
Hypothesis testing is a cornerstone of inferential statistics. It underpins scientific research, A/B testing, and model validation.
10. Kernel Density Estimation (KDE) with Seaborn
While histograms are a quick way to see the shape of data, they still depend heavily on bin size. Kernel Density Estimation (KDE) provides a smoother and more continuous view of the underlying probability distribution. It’s especially helpful when comparing multiple distributions or when you want to highlight subtle patterns in the data.
import seaborn as sns import numpy as np import matplotlib.pyplot as plt # Generate 1000 samples from a normal distribution with mean=0 and std=1 data = np.random.normal(0, 1, 1000) # Plot a kernel density estimate (KDE) of the distribution sns.kdeplot(data, fill=True) plt.show()
This one-liner sns.kdeplot(data, fill=True) creates a smooth curve that estimates the probability density of the data. Unlike a histogram, which uses discrete bins, KDE uses kernels to “smooth out” the distribution, giving a clearer picture of where the data is concentrated.
KDE plots are widely used in exploratory data analysis (EDA) and are a core feature of libraries like Seaborn. They are often combined with other plots, such as boxplots or scatterplots, to enhance insights.
Conclusion
In this article, we explored ten Python one-liners that highlight how randomness, averages, sampling, and hypothesis testing can be expressed concisely. From the uniform distribution’s simplicity to the flexibility of kernel density estimation, each example showed a different perspective on how probability helps us model the world.
These one-liners are not production-ready tools, but they are powerful for learning and experimentation. Once you understand them, you can extend the ideas to larger datasets, statistical modeling, and machine learning. For instance, libraries like SciPy, NumPy, and Seaborn provide full-featured implementations for serious analysis.
If you’re looking to go further, here are some valuable resources:
- Think Stats (2nd Edition) by Allen B. Downey for a free, Python-based introduction to statistics
- Statistical functions in SciPy for hands-on tools you can apply directly in projects
