Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

54 matches
Strings & text easy

How to Sort Text Alphabetically in Python

Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.

sorting text-processing strings
Python
def sort_words(text):
    """Sort words alphabetically (case-insensitive), preserving case."""
    words = text.split()
    return sorted(words, key=str.lower)


def sort_lines(text):
    """Sort lines alphabetically (case-insensitive), preserving case."""
    lines = [line for line in text.splitlines() if line.strip(…
11 0 Open
Strings & text easy

How to Sort Text in Python with a Simple Helper Function

A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.

sorting strings text-processing
Python
def sort_text(data, reverse=False):
    """
    Sort a list of strings (or a single string split into words) alphabetically.
    """
    if isinstance(data, str):
        words = data.split()
    else:
        words = [str(item) for item in data]
    return sorted(words, reverse=reverse)


if __name__ == "__main__":
 …
11 0 Open
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
44 0 Open
Lists & loops easy

How to Find the Third Smallest Element in a Python List

Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.

sorting lists unique
Python
def find_third_smallest(numbers):
    if len(numbers) < 3:
        return None
    
    unique_sorted = sorted(set(numbers))
    
    if len(unique_sorted) < 3:
        return None
    
    return unique_sorted[2]


if __name__ == "__main__":
    sample = [5, 2, 8, 2, 9, 1, 7, 3]
    result = find_third_smallest(sampl…
15 0 Open
Lists & loops easy

How to Merge Two Sorted Lists in Python

Merge two sorted lists into one sorted list using a two-pointer loop, then extend with remaining elements.

sorting merge two-pointers
Python
def merge_sorted_lists(list1, list2):
    merged = []
    i = j = 0
    
    while i < len(list1) and j < len(list2):
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1
    
    merged.extend(list1[i:])
    merged…
14 0 Open
Lists & loops easy

How to Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

partition list pivot
Python
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__…
14 0 Open
Lists & loops easy

How to Sort a List in Python in Ascending and Descending Order

This code demonstrates three ways to sort a list in Python: returning a new sorted list with sorted(), reversing the sort order, and sorting a list in place with the list.sort() method.

sort sorted lists
Python
def get_sorted_data(numbers):
    """Return a new list sorted in ascending order."""
    return sorted(numbers)


def reverse_sort(data):
    """Return a new list sorted in descending order."""
    return sorted(data, reverse=True)


def sort_in_place(data):
    """Sort the given list in place (modifies original)."""
…
12 0 Open
Lists & loops easy

How to Sort a List of Tuples by the Second Element in Python

Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.

sorting tuples lambda
Python
def sort_tuples_by_second(tuples_list):
    """Sort a list of tuples by the second element."""
    return sorted(tuples_list, key=lambda x: x[1])


if __name__ == "__main__":
    data = [(1, 5), (3, 2), (2, 8), (4, 1)]
    sorted_data = sort_tuples_by_second(data)
    print("Original list:", data)
    print("Sorted by…
13 0 Open
Functions & basics easy

How to Sort a List of Dictionaries by Key with a Lambda in Python

Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.

sorting lambda dictionaries
Python
def get_students():
    return [
        {"name": "alice", "score": 85},
        {"name": "bob", "score": 92},
        {"name": "carol", "score": 78},
        {"name": "dave", "score": 92},
    ]

students = get_students()

sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
13 0 Open
Functions & basics easy

How to Sort a List of Numbers in Python with Default Parameters

Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.

sorting default-parameters functions
Python
def sort_numbers(numbers, reverse=False):
    """Sort a list of numbers in ascending or descending order."""
    return sorted(numbers, reverse=reverse)


def main():
    numbers = [5, 2, 9, 1, 7, 3]
    
    # Default sort (ascending)
    ascending = sort_numbers(numbers)
    print(f"Ascending: {ascending}")
    
   …
13 0 Open
Functions & basics easy

How to Use Lambda Sorting Keys in Python

Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.

lambda sorting beginner
Python
# Demonstrate lambda as a sorting key function

students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob", "grade": 92},
    {"name": "Charlie", "grade": 75},
    {"name": "Diana", "grade": 95}
]

# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
15 0 Open
Functions & basics easy

How to Use a Lambda Sort Key in Python

Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.

lambda sorting sorted
Python
def sort_words(words):
    """Sort words by length, then alphabetically using a lambda key."""
    return sorted(words, key=lambda word: (len(word), word))

if __name__ == "__main__":
    sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
    result = sort_words(sample_words)
    
    print("Original:", sampl…
15 0 Open
Functions & basics easy

How to Use a Lambda Sorting Key in Python

Sort a list of strings by their last letter using a lambda function as the sorting key.

sorting lambda key-function
Python
def get_last_letter(word):
    return word[-1]

words = ["banana", "apple", "cherry", "date", "elderberry"]

if __name__ == "__main__":
    sorted_words = sorted(words, key=get_last_letter)
    print(sorted_words)
12 0 Open
Functions & basics easy

Sort a List of Dictionaries by Key in Python

Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.

lambda sorting list
Python
def get_items():
    return [
        {"name": "apple", "price": 3},
        {"name": "banana", "price": 1},
        {"name": "cherry", "price": 2},
    ]

if __name__ == "__main__":
    items = get_items()
    sorted_items = sorted(items, key=lambda item: item["price"])
    for item in sorted_items:
        print(f"{…
12 0 Open
Files & data easy

How to Sort Files by Name and Size in Python

Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.

sorting files lambda
Python
from pathlib import Path

def sort_files_data(files):
    """Sort a list of file dictionaries by name, then by size."""
    return sorted(files, key=lambda f: (f["name"], f["size"]))

if __name__ == "__main__":
    files_data = [
        {"name": "report.pdf", "size": 2048},
        {"name": "data.csv", "size": 1024},…
13 0 Open
Dictionaries & sets easy

How to Convert a Counter to a Plain Dict with Sorted Items in Python

This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.

counter dict sorting
Python
from collections import Counter

def counter_to_sorted_dict(counter):
    """Convert a Counter to a plain dict with sorted items."""
    return dict(sorted(counter.items()))

if __name__ == "__main__":
    # Example usage
    data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
    print("…
13 0 Open
Dictionaries & sets easy

How to Sort Dictionary Keys Alphabetically in Python

This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.

sorting dictionary case-insensitive
Python
data = {
    "banana": 3,
    "apple": 1,
    "Cherry": 5,
    "date": 2,
    "apple": 4,
    "Fig": 6,
    "banana": 2,
}

def sort_dict_keys_alphabetically(d):
    """Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
    return sorted(d.keys(), key=lambda k: k.lower())

if __n…
11 0 Open
Dictionaries & sets easy

How to Sort a List of Dictionaries by Key in Python

Sort a list of dictionaries by various keys (grade, age, name) using lambda, itemgetter, and extract unique sorted names into a set.

sorting dictionaries sets
Python
from operator import itemgetter

# Sample data: a list of dictionaries representing students
students = [
    {"name": "Alice", "grade": 88, "age": 23},
    {"name": "Bob", "grade": 95, "age": 22},
    {"name": "Charlie", "grade": 78, "age": 24},
    {"name": "Diana", "grade": 92, "age": 21}
]

# Sort by grade (descen…
12 0 Open
Dictionaries & sets easy

How to Sort a Python Dictionary by Value Descending

Sort dictionary items by their values in descending order and return a new dictionary.

dictionary sorting values
Python
def sort_dict_by_value_desc(d):
    return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))


if __name__ == "__main__":
    sample = {"apple": 5, "banana": 2, "cherry": 8, "date": 8}
    result = sort_dict_by_value_desc(sample)
    print(result)
12 0 Open
OOP & classes easy

How to Compare Dataclass Instances by Specific Fields in Python

Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.

dataclasses comparison sorting
Python
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class Person:
    name: str = field(compare=False)
    age: int
    height_cm: float
    priority: int = field(compare=False, default=0)

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age}, height={s…
14 0 Open
OOP & classes easy

How to Implement Rich Comparison Ordering in Python Classes

This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.

rich comparison sorting operators
Python
class Task:
    def __init__(self, priority, name):
        self.priority = priority
        self.name = name

    def __lt__(self, other):
        if not isinstance(other, Task):
            return NotImplemented
        return self.priority < other.priority

    def __eq__(self, other):
        if not isinstance(oth…
12 0 Open
OOP & classes easy

How to Sort Data in Python with a Class Helper

This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.

oop sorting sorted
Python
class DataSorter:
    def __init__(self, data):
        self.data = data

    def sort_numbers(self, reverse=False):
        return sorted(self.data, reverse=reverse)

    def sort_strings_ignore_case(self, reverse=False):
        return sorted(self.data, key=str.lower, reverse=reverse)

    def sort_dicts_by_key(self…
14 0 Open
OOP & classes medium

Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python

Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.

strategy-pattern oop abstract-class
Python
from abc import ABC, abstractmethod
from typing import List


class SortStrategy(ABC):
    @abstractmethod
    def sort(self, data: List[int]) -> List[int]:
        pass


class BubbleSort(SortStrategy):
    def sort(self, data: List[int]) -> List[int]:
        result = data[:]
        n = len(result)
        for i in…
12 0 Open
Algorithms & data structures medium

Find All Triplets with Sum Zero in Python

This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.

triplets two-pointers sorting
Python
def find_triplets(nums):
    nums.sort()
    n = len(nums)
    triplets = []
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
    …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.