Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

4 matches
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
Algorithms & data structures easy

Find Pivot Index in Python

Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.

pivot array prefix-sum
Python
def find_pivot_index(nums):
    total = sum(nums)
    left_sum = 0
    for i, num in enumerate(nums):
        if left_sum == total - left_sum - num:
            return i
        left_sum += num
    return -1


if __name__ == "__main__":
    test_cases = [
        [1, 7, 3, 6, 5, 6],
        [1, 2, 3],
        [2, 1, -…
13 0 Open
Data pipelines & processing easy

How to Unpivot Wide to Long with pandas melt in Python

This code demonstrates how to use pandas.melt to unpivot a wide DataFrame into a tidy long format, converting subject columns into rows.

pandas melt reshape
Python
import pandas as pd

# Sample wide-format data
df_wide = pd.DataFrame({
    'id': [1, 2, 3],
    'name': ['Alice', 'Bob', 'Charlie'],
    'math': [90, 85, 95],
    'science': [80, 92, 88]
})

print("Original wide DataFrame:")
print(df_wide)

# Melt: unpivot subject columns into rows
df_long = pd.melt(
    df_wide,
   …
15 0 Open
Big data & Spark easy

How to Pivot and Group Aggregate in Python

Group records by a key, collect values, and apply an aggregate function (like sum) to build a pivot-style summary dictionary.

pivot group-by aggregation
Python
from collections import defaultdict

def pivot_group_aggregate(records, group_key, value_key, agg_func):
    groups = defaultdict(list)
    for record in records:
        groups[record[group_key]].append(record[value_key])
    return {key: agg_func(values) for key, values in groups.items()}

if __name__ == "__main__":…
13 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.