Reference library

Python Code Samples

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

56 matches
Strings & text easy

How to Split Lines and Strip Blank Lines in Python

Split a multiline string into non-empty lines and strip surrounding whitespace using a list comprehension.

string splitlines strip
Python
import sys

def split_and_strip(text):
    """Split text into non-blank lines, stripping whitespace."""
    return [line.strip() for line in text.splitlines() if line.strip()]

if __name__ == "__main__":
    sample_text = """  First line   
    
    Second line	
      
    Third line  """
    result = split_and_strip(…
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
Strings & text easy

How to Split a String by Comma in Python

Splits a comma-separated string into a list of trimmed items using Python's built-in split and a list comprehension.

strings split list
Python
def split_csv(line):
    return [item.strip() for item in line.split(",")]

if __name__ == "__main__":
    sample = "apple, banana, cherry, date"
    result = split_csv(sample)
    print(result)
    print(f"Number of items: {len(result)}")
11 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 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 Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 0 Open
Lists & loops easy

How to Parse a Comma String into a List of Integers in Python

Converts a comma-separated string into a list of integers, handling spaces and empty inputs.

csv parsing list-comprehension
Python
def parse_csv_to_ints(text: str) -> list[int]:
    """Parse a comma-separated string into a list of integers."""
    if not text.strip():
        return []
    return [int(part.strip()) for part in text.split(",") if part.strip()]

if __name__ == "__main__":
    sample = "10, 20, 30, 40, 50"
    result = parse_csv_to_…
13 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 into Chunks in Python

Split a list into fixed-size sublists using a simple list comprehension with slicing.

list slicing chunking
Python
def chunk_list(lst, size):
    """Split a list into sublists of given size."""
    return [lst[i:i + size] for i in range(0, len(lst), size)]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(chunk_list(sample, 3))
13 0 Open
Lists & loops easy

Pairwise Adjacent Differences in a Python List

Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.

list-comprehension differences absolute-value
Python
def adjacent_differences(nums):
    """Return list of absolute differences between adjacent elements."""
    return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]


if __name__ == "__main__":
    sample = [3, 7, 2, 9, 5]
    diffs = adjacent_differences(sample)
    print("Original list:", sample)
    print…
14 0 Open
Lists & loops easy

Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

list-comprehension data-cleaning list-transformation
Python
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")
14 0 Open
Functions & basics easy

Benchmark list append vs comprehension in Python

This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.

timeit benchmark performance
Python
import timeit

# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
    result = []
    for i in range(n):
        result.append(i)
    return result

# Build the same list using a list comprehension
def comprehension(n=1_000_000):
    return [i for i in range(n)]

if __n…
13 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
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 Build a Gradebook with Python Dictionaries and Sets

Create a gradebook dictionary from student names and grades, find top students with a set comprehension, and add extra credit with a dict comprehension.

dictionaries sets comprehensions
Python
def build_gradebook(students, grades):
    """Create a dictionary mapping student names to their grades."""
    return dict(zip(students, grades))


def find_top_students(gradebook, passing_grade=60):
    """Return a set of students with grades at or above the passing grade."""
    return {name for name, grade in grad…
12 0 Open
Dictionaries & sets easy

How to Extract Data by Category in Python with Dictionaries and Sets

Use set comprehensions and a defaultdict to extract product names by category and compute total prices per category from a list of dictionaries.

dictionaries sets comprehensions
Python
from collections import defaultdict

# Sample data: products with categories and prices
product_data = [
    {"name": "Apple", "category": "fruit", "price": 0.50},
    {"name": "Banana", "category": "fruit", "price": 0.30},
    {"name": "Carrot", "category": "vegetable", "price": 0.80},
    {"name": "Bread", "category…
12 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…
14 0 Open
Dictionaries & sets easy

How to Map Dictionary Values with a Transformation Function in Python

Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.

dictionaries mapping comprehension
Python
def transform_dict_values(d, func):
    """Apply a transformation function to every value in a dictionary."""
    return {key: func(value) for key, value in d.items()}


if __name__ == "__main__":
    original = {"a": 1, "b": 2, "c": 3}
    doubled = transform_dict_values(original, lambda x: x * 2)
    print(doubled)
…
14 0 Open
Dictionaries & sets easy

How to Normalize Data in Python with Dictionaries and Sets

Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.

dictionaries sets data-cleaning
Python
def normalize_data(data, keys):
    """
    Normalize a list of dictionaries by keeping only specified keys
    and converting values to proper types.
    """
    normalized = []
    for item in data:
        clean_item = {}
        for key in keys:
            value = item.get(key)
            if isinstance(value, st…
12 0 Open
Dictionaries & sets easy

How to Validate Required Dict Keys in Python

Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.

dictionary validation missing-keys
Python
def find_missing_keys(data: dict, required_keys: list) -> list:
    """Return a list of required keys that are missing from the dictionary."""
    return [key for key in required_keys if key not in data]


if __name__ == "__main__":
    user_data = {
        "name": "Alice",
        "email": "alice@example.com",
     …
12 0 Open
Dictionaries & sets easy

How to swap dict keys and values in Python when values are unique

Swap dict keys and values using a dict comprehension, with a guard that raises an error when values repeat.

dictionary comprehension keys-values
Python
def swap_dict_keys_values(d):
    """Swap keys and values in a dict, assuming values are unique."""
    if len(set(d.values())) != len(d.values()):
        raise ValueError("Values must be unique to swap keys and values")
    return {v: k for k, v in d.items()}

if __name__ == "__main__":
    original = {"a": 1, "b": …
14 0 Open
Algorithms & data structures easy

Filter List to Keep Only Whitelist Values in Python

Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.

filtering sets list-comprehension
Python
def filter_whitelist(values, whitelist):
    """Return only values that are present in the whitelist set."""
    return [value for value in values if value in whitelist]

if __name__ == "__main__":
    raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
    allowed = {"apple", "banana", "date"}

…
11 0 Open
Algorithms & data structures easy

Find All Indices of a Target Value in a Python List

Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.

list index enumerate
Python
def find_all_indices(arr, target):
    return [i for i, value in enumerate(arr) if value == target]

if __name__ == "__main__":
    sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
    target = 2
    result = find_all_indices(sample_list, target)
    print(result)
13 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

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.