Reference library

Python Code Samples

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

18 matches
Strings & text easy

How to Count Vowels in a String in Python

Counts uppercase and lowercase vowels in a given string using a set and a generator expression.

strings vowels counting
Python
def count_vowels(text):
    vowels = set("aeiouAEIOU")
    return sum(1 for char in text if char in vowels)

if __name__ == "__main__":
    sample = "Hello, World!"
    result = count_vowels(sample)
    print(f"Vowel count in '{sample}': {result}")
12 0 Open
Lists & loops easy

Check if List is Sorted Ascending in Python

Verify that a list is sorted in ascending order using the all() function and a generator expression.

lists sorted all
Python
def is_sorted_ascending(lst):
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

if __name__ == "__main__":
    test_lists = [
        [1, 2, 3, 4, 5],
        [1, 3, 2, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3],
        [10],
        []
    ]
    for lst in test_lists:
        print(f"{l…
19 0 Open
Lists & loops easy

Convert a List of Integers to a Comma-Separated String in Python

Convert a list of integers into a single comma-separated string using a generator expression and str.join.

join list comma
Python
def ints_to_comma_string(numbers):
    return ",".join(str(num) for num in numbers)

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    result = ints_to_comma_string(numbers)
    print(result)
15 0 Open
Lists & loops easy

How to Check if a List is Sorted in Descending Order in Python

This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.

sorted descending list
Python
def is_descending(lst):
    """Return True if list is sorted in descending order."""
    return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))


if __name__ == "__main__":
    test_cases = [
        [5, 4, 3, 2, 1],
        [3, 3, 2, 1],
        [1, 2, 3],
        [10, 8, 9],
        []
    ]

    for case in …
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

Convert Data in Python with Comprehensions and Generators

Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.

comprehensions generators list-comprehension
Python
def convert_numbers(data):
    """Convert a list of mixed values into integers using a comprehension."""
    return [int(item) for item in data if item is not None]


def double_even_numbers(numbers):
    """Double only even numbers using a generator expression."""
    return (n * 2 for n in numbers if n % 2 == 0)


d…
15 0 Open
Comprehensions & generators easy

Count Data in Python with Comprehensions and Generators

Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.

comprehensions generators counter
Python
from collections import Counter

data = ["apple", "banana", "apple", "cherry", "banana", "apple"]

counts = {item: data.count(item) for item in set(data)}

square_gen = (x * x for x in range(5))
squares = list(square_gen)

if __name__ == "__main__":
    print("Manual count:", counts)
    print("Counter:", dict(Counter…
15 0 Open
Comprehensions & generators easy

Generate Data with Python Comprehensions and Generators

Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.

comprehensions generators lazy-evaluation
Python
# Data generation helpers using comprehensions and generators
from itertools import islice


def fibonacci(limit):
    """Generate Fibonacci numbers up to a limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


def main():
    # List comprehension: squares of even numbers
    square…
15 0 Open
Comprehensions & generators medium

How to Generate Primes with a Generator in Python

Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.

generators sieve primes
Python
def prime_generator(limit):
    sieve = [True] * (limit + 1)
    sieve[0] = sieve[1] = False

    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, limit + 1, i):
                sieve[j] = False

    return (num for num, is_prime in enumerate(sieve) if is_prime)


if __n…
15 0 Open
Comprehensions & generators easy

How to Parse Data with Generators and Comprehensions in Python

This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.

generator expressions dictionary comprehensions filtering
Python
def parse_data_helper(raw_records):
    """Extract active users' names and scores from raw records."""
    parsed = (
        (record["name"], record["score"])
        for record in raw_records
        if record["active"] and record["score"] >= 0
    )
    return list(parsed)


def aggregate_scores(parsed_data):
    "…
15 0 Open
Comprehensions & generators easy

How to Split Data into Chunks and Use Generators in Python

Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.

comprehensions generators chunking
Python
def split_numbers(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def square_even_numbers(numbers):
    return (n ** 2 for n in numbers if n % 2 == 0)


if __name__ == "__main__":
    sample_data = list(range(1, 21))
    chunks = split_numbers(sample_data, 5)
    print…
15 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators in Python

Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.

comprehensions generators yield
Python
def demonstrate_comprehensions_generators():
    # List comprehension: transform and filter in one line
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    squares = [num ** 2 for num in numbers if num % 2 == 0]
    print(f"Square of even numbers (list comprehension): {squares}")

    # Set comprehension: unique values
…
15 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators in Python

Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.

comprehensions generators list-comprehension
Python
def analyze_numbers(numbers):
    squared = [n ** 2 for n in numbers if n % 2 == 0]
    total = sum(n for n in numbers)
    max_squared = max((n ** 2 for n in numbers), default=0)
    return squared, total, max_squared


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6]
    evens_squared, total_sum, max_sq = an…
11 0 Open
Comprehensions & generators easy

Merge Data with Comprehension and Generator in Python

Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.

dictionary-comprehension generator-expression data-merging
Python
def merge_data(users, orders):
    """
    Merge user and order data using a dictionary comprehension
    and a generator expression for filtering.
    """
    # Build a lookup: user_id -> user name
    user_map = {user["id"]: user["name"] for user in users}

    # Generator: yield orders with user names attached
    …
14 0 Open
Comprehensions & generators easy

Normalize Data in Python with Comprehensions and Generators

Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.

comprehensions generators normalization
Python
import statistics

# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]

# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]

# Normalize using min-max scaling with a generator expression
min_val = min(clea…
13 0 Open
Comprehensions & generators easy

Python Comprehensions and Generators for Beginners

Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.

comprehensions generators lazy-evaluation
Python
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators

def demonstrate_comprehensions():
    # List comprehension: squares of even numbers
    numbers = range(1, 11)
    even_squares = [n ** 2 for n in numbers if n % 2 == 0]
    
    # Dict comprehension: number to its factorial
 …
15 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 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.