Reference library

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

1 match
Lists & loops easy

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.

lists padding slicing
Python
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…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Lists & loops — Python code examples

What you will find here

This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.