K-Means Clustering
Step-by-step understanding.
K-Means Clustering is a free Python Academy lesson on CoddyKit. This is lesson 2 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 5 lessons in total.
K-Means Clustering
K-Means is one of the most popular clustering algorithms. It partitions data into a predefined number of clusters (K) by minimizing the intra-cluster distances.
It works iteratively to find the best cluster assignments and centroids.

How K-Means Works
K-Means operates in the following steps:
- Initialize K random centroids.
- Assign each data point to the nearest centroid.
- Recalculate centroids as the mean of all points in a cluster.
- Repeat steps 2 and 3 until centroids stabilize or a maximum number of iterations is reached.
Choosing the Number of Clusters
The value of K is a critical parameter. Common methods to choose K include:
- Elbow Method: Plot the within-cluster sum of squares (WCSS) for different K values and look for the 'elbow point.'
- Silhouette Score: Measures how well-separated the clusters are.
Example Dataset for K-Means
Let’s consider a dataset with points distributed in 2D space. Each point has:
- X: Coordinate on the horizontal axis.
- Y: Coordinate on the vertical axis.
K-Means will group these points into clusters based on their proximity.
Implementing K-Means in Python
We’ll use the KMeans class from the scikit-learn library to implement the algorithm:
from sklearn.cluster import KMeans
import numpy as np
# Example dataset
X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
# K-Means model
kmeans = KMeans(n_clusters=2, random_state=0)
kmeans.fit(X)
print("Cluster Centers:", kmeans.cluster_centers_)
print("Labels:", kmeans.labels_)Visualizing Clusters
We can visualize the clusters by plotting the data points and centroids:
import matplotlib.pyplot as plt
# Scatter plot of data points
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
# Plot cluster centers
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red', marker='X')
plt.title('K-Means Clustering')
plt.show()Advantages of K-Means
K-Means has several benefits:
- Simple and easy to implement.
- Efficient for large datasets.
- Works well when clusters are clearly defined.
Limitations of K-Means
Some limitations of K-Means include:
- Sensitivity to the initial placement of centroids.
- Difficulty in handling non-spherical clusters.
- Sensitivity to outliers and noisy data.
Summary and Next Steps
In this lesson, we covered:
- How K-Means clustering works.
- Choosing the number of clusters using methods like the elbow method.
- Implementing and visualizing K-Means in Python.
Next, we will apply K-Means to a real-world dataset to gain practical experience.

Learn Python with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 76
- Lessons
- 320
Frequently Asked Questions
Is the “K-Means Clustering” lesson free?
Yes — the full text of “K-Means Clustering” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 5 lessons in total.
What will I learn in “K-Means Clustering”?
Step-by-step understanding. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 5.
How long does the “K-Means Clustering” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Introduction to Clustering Algorithms
- K-Means Clustering
- K-Means Clustering Project
- Dimensionality Reduction Basics
- Dimensionality Reduction Application