Python
Packing Algorithm
Algorithm Implementation
Software Development
Computational Efficiency

Python Implementations of Packing Algorithm

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Packing algorithms decide how to place items into limited space while wasting as little capacity as possible. In Python, the most common starting point is one-dimensional bin packing, where each item has a size and every bin has the same capacity. The exact optimal solution is hard in general, so many real systems use heuristics.

A Simple Bin-Packing Model

In the standard one-dimensional version:

  • each item has a size such as 4, 7, or 2
  • every bin has the same capacity such as 10
  • the goal is to use as few bins as possible

This is a good fit for packaging, container assignment, memory partitioning, and batch scheduling problems where capacity is the dominant constraint.

The key practical point is that a good heuristic is often more valuable than an expensive exact solver.

First-Fit Heuristic

A classic baseline is first-fit. Process items in order and place each item into the first bin that has enough remaining space.

python
1def first_fit(items, capacity):
2    bins = []
3
4    for item in items:
5        placed = False
6        for current_bin in bins:
7            if sum(current_bin) + item <= capacity:
8                current_bin.append(item)
9                placed = True
10                break
11
12        if not placed:
13            bins.append([item])
14
15    return bins
16
17
18items = [4, 8, 1, 4, 2, 1]
19result = first_fit(items, 10)
20print(result)
21print("bins used:", len(result))

This is easy to implement and easy to explain, which makes it a good first version in Python.

First-Fit Decreasing

Item order matters a lot. A stronger baseline is first-fit decreasing, which sorts items from largest to smallest before packing them.

python
1def first_fit_decreasing(items, capacity):
2    sorted_items = sorted(items, reverse=True)
3    bins = []
4
5    for item in sorted_items:
6        placed = False
7        for current_bin in bins:
8            if sum(current_bin) + item <= capacity:
9                current_bin.append(item)
10                placed = True
11                break
12
13        if not placed:
14            bins.append([item])
15
16    return bins
17
18
19items = [4, 8, 1, 4, 2, 1]
20result = first_fit_decreasing(items, 10)
21print(result)
22print("bins used:", len(result))

For many practical inputs, this performs noticeably better than unsorted first-fit with almost no extra complexity.

A More Efficient Python Representation

The simple versions above repeatedly call sum(current_bin), which becomes wasteful as bins grow. A better implementation tracks remaining capacity directly.

python
1def first_fit_fast(items, capacity):
2    bins = []
3    remaining = []
4
5    for item in items:
6        placed = False
7        for index, free_space in enumerate(remaining):
8            if item <= free_space:
9                bins[index].append(item)
10                remaining[index] -= item
11                placed = True
12                break
13
14        if not placed:
15            bins.append([item])
16            remaining.append(capacity - item)
17
18    return bins, remaining
19
20
21items = [7, 5, 6, 2, 3, 7, 2]
22bins, remaining = first_fit_fast(items, 10)
23print(bins)
24print(remaining)

This keeps the code readable while avoiding repeated total recomputation.

When You Need Better Than a Heuristic

Heuristics are fast and easy to maintain, but they do not prove optimality. If the dataset is small and exact answers matter, use an optimization solver such as OR-Tools or PuLP and model the problem as integer programming.

That tradeoff is common:

  • heuristics are fast and simple
  • exact solvers can find better packings but cost more runtime and implementation effort

For many business workloads, a good heuristic with metrics and monitoring is the pragmatic answer.

Packing Is Not Only Bin Packing

People use the phrase "packing algorithm" for several different problems, including:

  • bin packing
  • knapsack
  • rectangle packing
  • pallet or container loading

That distinction matters because the right algorithm depends on the model. A one-dimensional bin-packing heuristic does not automatically solve a two-dimensional layout problem.

Common Pitfalls

The most common mistake is assuming item order does not matter. For greedy packing heuristics, order can change the result significantly.

Another mistake is treating a heuristic result as if it were guaranteed optimal. A valid packing is not automatically the best packing.

People also apply a one-dimensional algorithm to a problem that is really two-dimensional or value-based. Once width, height, orientation, or item value matters, the model has changed.

Finally, avoid overcomplicating the first version. In Python, a clear heuristic is often the right place to start before reaching for heavier optimization libraries.

Summary

  • Bin packing is a common and practical form of packing algorithm.
  • First-fit is easy to implement but sensitive to item order.
  • First-fit decreasing is often a better baseline with little extra code.
  • Tracking remaining capacity explicitly makes Python implementations more efficient.
  • Use an exact solver only when heuristic quality is not good enough for the real problem.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.