Reference library

Lists & loops

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

2 matches
Lists & loops easy

Check if List is Sorted Ascending in Python

Verify that a list is sorted in ascending order using the all() function and a generator expression.

lists sorted all
Python
def is_sorted_ascending(lst):
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

if __name__ == "__main__":
    test_lists = [
        [1, 2, 3, 4, 5],
        [1, 3, 2, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3],
        [10],
        []
    ]
    for lst in test_lists:
        print(f"{l…
19 0 Open
Lists & loops easy

Truncate List Keeping Last N Elements in Python

Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.

list slicing sequence
Python
def truncate(seq, keep_last_n):
    """Return a new list keeping only the last n elements."""
    if keep_last_n <= 0:
        return []
    return list(seq)[-keep_last_n:]


if __name__ == "__main__":
    data = [10, 20, 30, 40, 50, 60]
    print(truncate(data, 3))
    print(truncate(data, 0))
    print(truncate(data…
11 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.