Reference library

Python Code Samples

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

16 matches
Lists & loops easy

How to Interleave Two Lists in Python Until One List Exhausted

Interleave elements from two lists pairwise using zip, stopping when either list runs out of items.

zip lists interleave
Python
def interleave(a, b):
    result = []
    for x, y in zip(a, b):
        result.extend([x, y])
    return result

if __name__ == "__main__":
    list1 = [1, 2, 3, 4, 5]
    list2 = ["a", "b", "c"]
    print(interleave(list1, list2))
12 0 Open
Lists & loops easy

How to Zip Two Lists into Pairs in Python

Combine two lists element-wise into a list of tuples using Python's built-in zip() function.

zip lists tuples
Python
def zip_lists_into_pairs(list1, list2):
    pairs = list(zip(list1, list2))
    return pairs

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    quantities = [3, 5, 2]
    result = zip_lists_into_pairs(fruits, quantities)
    print(result)
14 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
13 0 Open
Files & data easy

Compress and Extract ZIP Files Programmatically in Python

Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.

zip compression file-io
Python
import zipfile
from pathlib import Path
import tempfile
import os

def create_sample_zip(zip_path: str, files: dict) -> None:
    """Create a ZIP file containing the given files (name -> content mapping)."""
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for filename, content in files.ite…
99 0 Open
Files & data easy

Extract a Single Member from a ZIP Archive in Python

Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.

zipfile zip extraction
Python
import zipfile
from pathlib import Path

def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
    """Extract a single member from a zip archive to the output directory."""
    with zipfile.ZipFile(zip_path, "r") as archive:
        archive.extract(member_name, output_dir)
    retu…
19 0 Open
Files & data easy

How to Compress a String to Gzip Bytes in Python

Compress a string into gzip-compressed bytes entirely in memory using the standard library gzip module.

gzip compression bytes
Python
import gzip

def compress_to_gzip_bytes(data: str, encoding: str = "utf-8") -> bytes:
    """Compress a string to gzip-compressed bytes in memory."""
    return gzip.compress(data.encode(encoding))

if __name__ == "__main__":
    original = "Hello, world! " * 10
    compressed = compress_to_gzip_bytes(original)
    pr…
13 0 Open
Files & data easy

How to Decompress a gzip File in Python

This code provides a function to decompress a .gz file, writing the decompressed content to a new file and returning the text, using the gzip standard library module.

gzip decompression file-handling
Python
import gzip
from pathlib import Path

def decompress_gzip(filepath: str, output_path: str | None = None) -> str:
    """Decompress a .gz file and return the decompressed content."""
    input_path = Path(filepath)
    if output_path is None:
        output_path = str(input_path.with_suffix(""))
    
    with gzip.open…
12 0 Open
Dictionaries & sets easy

How to Create a Dict from Two Parallel Lists in Python (zip)

Build a dictionary by pairing elements from two parallel lists using Python's built-in zip function and dict constructor.

dictionary zip lists
Python
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]

result = dict(zip(keys, values))
print(result)
12 0 Open
Algorithms & data structures easy

How to Add Two Lists Elementwise in Python

Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.

list zip list-comprehension
Python
def elementwise_add(list1, list2):
    return [a + b for a, b in zip(list1, list2)]

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [10, 20, 30, 40]
    result = elementwise_add(list_a, list_b)
    print(result)
12 0 Open
Algorithms & data structures easy

How to Compare Two Lists Elementwise for Greater Flags in Python

Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.

lists comparison zip
Python
def compare_lists_greater(list_a, list_b):
    """
    Compare two lists elementwise and return a list of booleans
    indicating whether each element in list_a is greater than the
    corresponding element in list_b.
    """
    if len(list_a) != len(list_b):
        raise ValueError("Lists must have the same length"…
13 0 Open
Algorithms & data structures easy

How to Compute the Dot Product of Two Lists in Python

Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.

dot product zip sum
Python
def dot_product(list1, list2):
    """
    Compute the dot product of two numeric lists.
    The lists must have the same length.
    """
    if len(list1) != len(list2):
        raise ValueError("Lists must have the same length")
    
    return sum(a * b for a, b in zip(list1, list2))


if __name__ == "__main__":
  …
13 0 Open
Comprehensions & generators easy

How to Compress a Generator with a Boolean Mask in Python

Filters items from a generator based on a parallel boolean mask, yielding only the items where the mask is True.

generators zip filter
Python
def compress(generator, mask):
    for item, keep in zip(generator, mask):
        if keep:
            yield item


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    mask = [True, False, True, False, True]
    result = list(compress(iter(data), mask))
    print(result)
14 0 Open
Comprehensions & generators easy

How to Create a Pairwise Generator with zip and tee in Python

Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.

itertools generators zip
Python
from itertools import tee


def pairwise(iterable):
    """Yield successive overlapping pairs from iterable."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5]
    print(list(pairwise(values)))
    print(list(pairwise("hello")))
15 0 Open
Automation & scripting easy

How to Compress a Folder in Python While Preserving Directory Structure

A Python function that uses zipfile to recursively compress a folder, maintaining the original directory hierarchy inside the zip archive.

compression zipfile file-archiving
Python
import os
import zipfile
from pathlib import Path

def compress_folder(source_dir: str, output_zip: str):
    """
    Compress a folder into a zip file, preserving the directory structure.
    
    Args:
        source_dir: Path to the source directory to compress
        output_zip: Path for the output zip file
    "…
33 0 Open
Automation & scripting easy

How to Create a Password Protected Zip Archive in Python

Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.

zipfile password encryption
Python
import zipfile
import tempfile
import os


def create_password_protected_zip(zip_path, password: str, files: dict):
    """
    Create a zip archive with password protection (mock encryption).

    Args:
        zip_path: Path where the zip file will be created
        password: Password for the archive
        files:…
12 0 Open
Data pipelines & processing easy

How to Compress Pipeline Output Gzip Per Partition in Python

Compress each partition of pipeline output into a separate gzip file and verify the compressed data by reading it back.

gzip compression pipeline
Python
import gzip
import io
import random
from pathlib import Path


def compress_partition(partition_data: list[str], output_path: Path) -> int:
    """Compress a partition of data to a gzip file, returns bytes written."""
    with gzip.open(output_path, 'wt', encoding='utf-8') as f:
        f.writelines(partition_data)
  …
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.