Reference library

Python Code Samples

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

81 matches
Strings & text easy

How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

palindrome string case-insensitive
Python
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
      …
14 0 Open
Strings & text easy

How to Filter Text to Only Letters, Numbers, and Spaces in Python

A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.

text-filtering strings beginner
Python
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
    allowed = set()
    if keep_alpha:
        allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    if keep_digits:
        allowed.update("0123456789")
    if keep_spaces:
        allowed.add(" ")
    return "".join(ch f…
11 0 Open
Strings & text easy

How to Filter a List of Strings by Keyword in Python

A helper function filters a list of strings by a keyword search with optional case sensitivity.

string filter list
Python
def filter_strings(items, keyword, case_sensitive=False):
    """
    Filter a list of strings by a keyword.
    
    Args:
        items: list of strings to filter
        keyword: substring to search for
        case_sensitive: if True, match case exactly
    
    Returns:
        list of strings containing the keyw…
12 0 Open
Strings & text easy

How to Split Strings in Python (Beginner-Friendly)

Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.

string split text parsing delimiter
Python
def split_text(text, delimiter=" "):
    """Split a string by a delimiter and return a list of parts."""
    return text.split(delimiter)


def split_text_with_cleanup(text, delimiter=" "):
    """Split a string, stripping whitespace and filtering empty parts."""
    parts = text.split(delimiter)
    cleaned = [part.s…
16 0 Open
Lists & loops easy

Extract Data by Type from a List in Python: Numbers and Strings

Loop through a mixed list to filter out numeric and string values into separate lists.

lists filtering type-checking
Python
def extract_numbers(items):
    """Extract all numeric values from a mixed list."""
    numbers = []
    for item in items:
        if isinstance(item, (int, float)) and not isinstance(item, bool):
            numbers.append(item)
    return numbers


def extract_strings(items):
    """Extract all string values from a…
14 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 Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
12 0 Open
Lists & loops easy

How to Filter Even Numbers and Square Them in Python

Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.

loops filtering math
Python
def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

def get_squares(numbers):
    squares = []
    for num in numbers:
        squares.append(num ** 2)
    return squares

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers …
15 0 Open
Lists & loops easy

How to Filter None Values from a Mixed List in Python

Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.

filter list-comprehension none
Python
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]

filtered_list = [item for item in mixed_list if item is not None]

print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
15 0 Open
Lists & loops easy

How to Filter a List in Python with a Loop

Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.

filter for-loop lists
Python
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18

adults = []
for age in ages:
    if age >= threshold:
        adults.append(age)

print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
10 0 Open
Lists & loops easy

How to Loop Through Lists in Python for Beginners

Transform, filter, sum, and find the maximum in a Python list using basic for loops and conditionals.

lists loops iteration
Python
def transform_data(numbers):
    """Basic transformation examples using lists and loops."""
    doubled = []
    for n in numbers:
        doubled.append(n * 2)
    return doubled


def filter_even(numbers):
    """Keep only even numbers using a loop and condition."""
    evens = []
    for n in numbers:
        if n …
14 0 Open
Lists & loops easy

How to Parse Bullet Points in Python

Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.

text parsing bullet points loops
Python
def parse_bullet_points(text):
    """Extract bullet point items from raw text."""
    lines = text.splitlines()
    items = []
    
    for line in lines:
        stripped = line.strip()
        if stripped.startswith("- ") or stripped.startswith("* "):
            item = stripped[2:]
            if item:
           …
13 0 Open
Lists & loops easy

How to Parse Delimited Data into a Python List

Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.

strings lists loops
Python
def parse_data(raw_data):
    """Parse a pipe-delimited string into a list of cleaned items."""
    items = raw_data.split("|")
    parsed = []
    for item in items:
        cleaned = item.strip()
        if cleaned:
            parsed.append(cleaned)
    return parsed


if __name__ == "__main__":
    data = "  apple…
15 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.

lists loops strings
Python
text = "Python makes text processing easy and fun"

words = text.lower().split()

print("Words in the sentence:")
for index, word in enumerate(words, start=1):
    print(f"{index}. {word}")

filtered_words = [word for word in words if len(word) > 3]

print(f"\nWords longer than 3 characters: {filtered_words}")

letter…
14 0 Open
Lists & loops easy

How to split a list by condition in Python

Splits a list into two lists based on a condition function, returning matched and unmatched items.

lists condition partition
Python
def split_by_condition(items, condition):
    """
    Split a list into two lists based on a condition.
    The first list contains items where condition(item) is True,
    the second list contains the rest.
    """
    matched = []
    unmatched = []
    for item in items:
        if condition(item):
            matc…
11 0 Open
Lists & loops easy

Intersection of Two Lists Preserving Order in Python

This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.

lists intersection order
Python
def intersection_preserving_order(list1, list2):
    """
    Return the intersection of two lists while preserving the order
    of elements as they appear in list1.
    """
    set2 = set(list2)
    result = []
    seen = set()
    
    for item in list1:
        if item in set2 and item not in seen:
            resu…
15 0 Open
Functions & basics easy

How to Pass a Function as a Callback to map and filter in Python

Shows how to apply custom functions to every element of a list using map and filter callbacks in Python.

map filter callbacks
Python
def double(x):
    return x * 2

def is_even(x):
    return x % 2 == 0

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = list(map(double, numbers))
    evens = list(filter(is_even, numbers))
    print("Original:", numbers)
    print("Doubled:", doubled)
    print("Evens:", evens)
16 0 Open
Functions & basics easy

Python Filter Function with Default Parameters for Beginners

Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.

functions default-parameters filter
Python
def filter_numbers(numbers, threshold=0, reverse=False):
    """Return numbers that pass the threshold filter.

    Args:
        numbers: list of numbers to filter
        threshold: minimum value to keep (default 0)
        reverse: if True, keep numbers below threshold (default False)
    """
    if reverse:
      …
13 0 Open
Files & data easy

Build a Simple ETL Pipeline in Python

A simple ETL pipeline that reads JSON Lines, transforms records with filtering and normalization, and writes the result to JSON.

etl json jsonl
Python
import json
from pathlib import Path


def read_input(file_path: Path) -> list[dict]:
    """Read JSON lines file into list of dicts."""
    with file_path.open("r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def transform(records: list[dict]) -> list[dict]:
    """Transf…
13 0 Open
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 0 Open
Files & data easy

How to Filter CSV Rows by Column Value in Python

Filter CSV rows based on a column value condition using the standard csv module and a lambda function.

csv filter file-io
Python
import csv

def filter_csv(input_file, output_file, column, condition):
    with open(input_file, newline='', encoding='utf-8') as infile, \
         open(output_file, 'w', newline='', encoding='utf-8') as outfile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames
        writer = csv.Dict…
19 0 Open
Files & data easy

How to Filter Files by Extension and Size in Python

Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.

pathlib filesystem filtering
Python
from pathlib import Path

def filter_files_by_extension(directory: str, extension: str) -> list:
    """Return a list of file names in directory with the given extension."""
    path = Path(directory)
    return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]

def filter_files_by_size(directo…
13 0 Open
Dictionaries & sets easy

Filter Dictionary Keys by Prefix in Python

Use a dict comprehension to build a new dictionary containing only keys that start with a given prefix.

dict-comprehension filtering dictionaries
Python
def filter_dict_keys(data, prefix="temp_"):
    """
    Filter a dictionary by keeping only keys that start with a given prefix.
    Uses a dict comprehension to build a new dictionary.
    """
    if not isinstance(data, dict):
        raise ValueError("data must be a dictionary")
    return {key: value for key, valu…
13 0 Open
Dictionaries & sets easy

How to Filter a Dictionary by Predicate on Values in Python

This code defines a reusable function that builds a new dictionary containing only the items whose values satisfy a given predicate function.

dictionary filtering lambda
Python
def filter_dict_by_predicate(d, predicate):
    """Return a new dict with only items whose value passes the predicate."""
    return {k: v for k, v in d.items() if predicate(v)}


if __name__ == "__main__":
    scores = {"Alice": 85, "Bob": 42, "Charlie": 91, "Diana": 60}
    # Keep only values greater than or equal t…
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.