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.
Python code
16 linesdef 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
[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
- Use `itertools.repeat` with `itertools.islice` for lazy padding on large lists: `list(islice(chain(lst, repeat(fill_value)), n))`
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.