How to Pad a List to Length n in Python with a Fill Value

Create a reusable function that pads a Python list to a specified length n by appending a fill value, or truncates it when the list is already longer than n.

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

Python code

16 lines
Python 3.9+
def pad_list(lst, n, fill_value=None):
    """
    Pad a list to length n using fill_value for missing elements.
    If the list is longer than n, it is truncated to length n.
    """
    if n <= len(lst):
        return lst[:n]
    return lst + [fill_value] * (n - len(lst))


if __name__ == "__main__":
    # Examples
    print(pad_list([1, 2, 3], 5, 0))          # Output: [1, 2, 3, 0, 0]
    print(pad_list(["a", "b"], 2))            # Output: ["a", "b"] (no padding needed)
    print(pad_list([1, 2, 3, 4], 2))          # Output: [1, 2] (truncated)
    print(pad_list([], 4, fill_value="x"))    # Output: ["x", "x", "x", "x"]

Output

stdout
[1, 2, 3, 0, 0]
['a', 'b']
[1, 2]
['x', 'x', 'x', 'x']

How it works

The function starts by checking whether the target length n is already less than or equal to the list's current length. If so, it returns a truncated slice lst[:n], which preserves the first n elements. Otherwise, it computes how many elements are missing (n - len(lst)) and appends that many copies of fill_value using list multiplication [fill_value] * count. The + operator concatenates the original list with the newly created filler list, producing the padded result. This approach is efficient because list multiplication and concatenation run in linear time relative to the output size.

Common mistakes

  • Mutating the input list in place instead of returning a new padded list, which can cause unexpected side effects
  • Using `range(n)` or loops when list multiplication `[fill_value] * count` is clearer and faster
  • Forgetting to handle the case where `n` is negative or zero — the function currently returns an empty list, which may not be intended

Variations

  1. Use `itertools.repeat` with `itertools.islice` for lazy padding on large lists: `list(islice(chain(lst, repeat(fill_value)), n))`
  2. Use the `more-itertools.padded` function if you're working in an environment where that library is already installed

Real-world use cases

  • Normalizing feature vectors to a fixed dimension before feeding them into a machine learning model.
  • Aligning rows of CSV data so all rows have the same number of columns when writing to a tabular file.
  • Padding fixed-width display tables in CLI tools or reports so columns line up consistently.

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.